This question already has answers here:
How to round up value C# to the nearest integer?
(10 answers)
Closed 7 years ago.
If I have a number, I would like it to output a rounded up number, like this:
1.12 = 2
1.30 = 2
0.89 = 1
Using Math.Round I was only able to get it to round up when it was over half.
Math.Ceiling should do the trick.
Returns the smallest integral value that is greater than or equal to
the specified double-precision floating-point number.
https://msdn.microsoft.com/en-us/library/zx4t0t48%28v=vs.110%29.aspx
static void Main(string[] args)
{
double temp1 = 1.12;
double temp2 = 1.30;
double temp3 = 0.89;
Console.WriteLine(Math.Ceiling(temp1));
//2
Console.WriteLine(Math.Ceiling(temp2));
//2
Console.WriteLine(Math.Ceiling(temp3));
//1
Console.ReadLine();
}
Please use Math.Ceiling instead.
There is Math.Ceiling for that
double dbl = Math.Ceiling(1.1); // 2
Note that
double dbl = Math.Ceiling(-1.1); // 1
Math.Ceiling returns the smallest integral value that is greater than or equal to the specified number.
int num = (int)Math.Ceiling(1.12);
Try using Math.Ceiling.
It will always round up :)
https://msdn.microsoft.com/en-us/library/zx4t0t48%28v=vs.110%29.aspx
Related
This question already has answers here:
Why do these division equations result in zero?
(10 answers)
Why does integer division in C# return an integer and not a float?
(8 answers)
Closed 4 years ago.
I'm calculating the percentage to add in a datagrid, but when I report the data it always returns me 0, what am I doing wrong?
if I have the following case: the variable quantidadeInstalada has the value of 10 and the goal has 20 the concluido would have to return me 50 but it returns me 0
private void AdicionarPessoa()
{
string Valida = ValidaPessoa();
if (Valida.Equals(""))
{
double concluido=0, falta=0;
int quantidadeInstalada = Convert.ToInt32(ttbQuantidade.Text);
int meta = Convert.ToInt32(ttbMetaPessoa.Text);
concluido = (quantidadeInstalada/meta)*100;
falta = 100-concluido;
MessageBox.Show(concluido.Text);
}
else
MessageBox.Show(Valida);
}
It's probably due to the precision of the int. Use a decimal or double instead.
When we use an integer, we lose precision.
Console.WriteLine(100 / 17); // 5
Console.WriteLine(100 / 17m); // 5.8823529411764705882352941176
Console.WriteLine(100 / 17d); // 5.88235294117647
Console.WriteLine(100 / 17f); // 5.882353
Since integers always round down, 0.99 as an integer is 0.
Note that for precision, the types of the inputs matters.
double output = input1 * input2;
For example:
double outputA = 9 / 10;
Console.WriteLine(outputA); // 0
double outputB = 9 / 10d;
Console.WriteLine(outputB); // 0.9
double outputC = 9d / 10;
Console.WriteLine(outputC); // 0.9
Here is a Fiddle.
It's because you're doing integer division. You can fix it by casting one of the variables to a double like this:
concluido = ((double)quantidadeInstalada/meta)*100;
When you're dividing int by int (as in "quantidadeInstalada/meta"), you'll get an int. Either use a fractional type (e.g. decimal, double) from the very beginning, as Shaun suggested, or (if the integral types have to stay), cast the values to a fractional type in the division expression (as itsme86 shown).
How do I divide two integers to get a double?
You want to cast the numbers:
double num3 = (double)num1/(double)num2;
Note: If any of the arguments in C# is a double, a double divide is used which results in a double. So, the following would work too:
double num3 = (double)num1/num2;
For more information see:
Dot Net Perls
Complementing the #NoahD's answer
To have a greater precision you can cast to decimal:
(decimal)100/863
//0.1158748551564310544611819235
Or:
Decimal.Divide(100, 863)
//0.1158748551564310544611819235
Double are represented allocating 64 bits while decimal uses 128
(double)100/863
//0.11587485515643106
In depth explanation of "precision"
For more details about the floating point representation in binary and its precision take a look at this article from Jon Skeet where he talks about floats and doubles and this one where he talks about decimals.
cast the integers to doubles.
Convert one of them to a double first. This form works in many languages:
real_result = (int_numerator + 0.0) / int_denominator
var firstNumber=5000,
secondeNumber=37;
var decimalResult = decimal.Divide(firstNumber,secondeNumber);
Console.WriteLine(decimalResult );
var result = decimal.ToDouble(decimal.Divide(5, 2));
I have went through most of the answers and im pretty sure that it's unachievable. Whatever you try to divide two int into double or float is not gonna happen.
But you have tons of methods to make the calculation happen, just cast them into float or double before the calculation will be fine.
The easiest way to do that is adding decimal places to your integer.
Ex.:
var v1 = 1 / 30 //the result is 0
var v2 = 1.00 / 30.00 //the result is 0.033333333333333333
In the comment to the accepted answer there is a distinction made which seems to be worth highlighting in a separate answer.
The correct code:
double num3 = (double)num1/(double)num2;
is not the same as casting the result of integer division:
double num3 = (double)(num1/num2);
Given num1 = 7 and num2 = 12:
The correct code will result in num3 = 0.5833333
Casting the result of integer division will result in num3 = 0.00
I'm trying convert a decimal into integer and want to round the value up or down depending on the situation.
Basically example is:
12/3 = 4 so should round to 4
11/3 = 3.66666 so should round to 4
10/3 = 3 = 3.33333 so should round to 3
9/3 = 3 so should round to 3
Whatever I found on the internet always rounds down or always rounds up, never makes a judgment call based on the numbers.
If x is the number you want to round and you want the "normal" rounding behavior (so that .5 always gets rounded up), you need to use Math.Round(x, MidpointRounding.AwayFromZero). Note that if you are actually computing fractions and the numerator and denominator are integers, you need to cast one of them to double first (otherwise, the division operator will produce an integer that is rounded down), and that if you want the result to be an int, you need to cast the result of Round():
int a = 5;
int b = 2;
double answer = (int) Math.Round(a / (double) b, MidpointRounding.AwayFromZero);
Math.Round(value) should do what you want. Examples console app code to demonstrate:
Console.Write("12 / 3 = ");
Console.WriteLine((int)Math.Round(12d / 3d));
Console.WriteLine();
Console.Write("11 / 3 = ");
Console.WriteLine((int)Math.Round(11d / 3d));
Console.WriteLine();
Console.Write("10 / 3 = ");
Console.WriteLine((int)Math.Round(10d / 3d));
Console.WriteLine();
Console.Write("9 / 3 = ");
Console.WriteLine((int)Math.Round(9d / 3d));
Console.WriteLine();
Console.ReadKey();
Does Math.Round(d) do what you require?
Return Value:
The integer nearest parameter d. If the fractional component of d is halfway between two integers, one of which is even and the other odd, the even number is returned. Note that this method returns a Decimal instead of an integral type.
Check out the Round reference page
You could try this
Math.Round(d, 0, MidpointRounding.AwayFromZero)
Sometime, people add 0.5 to the number before converting to int.
This question already has answers here:
How might I convert a double to the nearest integer value?
(8 answers)
Closed 9 years ago.
I'am producing decimal such as:
0.8235294117647058823529411765
0.1764705882352941176470588235
I'd like to multiply them by 10 then round them. If the second number after the dot is less than 5 then make it 0. Otherwise, make it 1. For the above examples, that would be:
8
2
The result should be put in a int.
I thought it is simple.
Math.Round(10 * your_decimal);
Reference: http://msdn.microsoft.com/en-us/library/3s2d3xkk.aspx
You can use Math.Round() if you want to keep it as a decimal or round to a certain precision.
decimal dec = 0.8235294117647058823529411765m;
decimal rounded = Math.Round(dec * 10); // 8m
decimal roundedToOne = Math.Round(dec * 10, 1); // 8.2m
FYI, an explicit conversion is defined for decimal to int so you can round down by casting to an int
int a = (int)(dec * 10); // 8
This could be combined with a condition to round the number up and down
decimal num = dec * 10;
int a = (int)num + (num % 0 < .5m ? 0 : 1); // 8
This question already has answers here:
How do I round to the nearest 0.5?
(10 answers)
Closed 9 years ago.
I'm trying to round some values as the following examples and need some help to write the math calculation for it:
input -> 25 ÷ 4 = 6.25 output -> 6.5
input -> 15.5 ÷ 4 = 3.875 output -> 4.0
input -> 24.5 ÷ 4 = 6.125 output -> 6.0
any idea how to write the round math procedure please?!
This should do it.
double Divide(double numerator, double denominator)
{
double result = numerator / denominator;
//round to nearest half-integer
result = Math.Round(result * 2, MidpointRounding.AwayFromZero) / 2;
// due to peculiarities of IEEE754 floating point arithmetic
// we need to round again after dividing back by two
// to avoid a result like 1.49999999.
return Math.Round(result, 1);
}
Sorry for not aware the difficulty you encountered, so I guess maybe the different types of floating point number. Following code just does that:
public static decimal RoundedDivide<T>(T a, T b) {
var x=2*Convert.ToDecimal(a)/Convert.ToDecimal(b);
x=((int)(.5m+x)>x?1:0)+(int)x;
return x/2;
}
Two things to note:
I cannot bound a constraint of ValueType, so if you pass objects of reference types, it may throw
If you wish double as the return type, then just change it and also change .5m to .5, Convert.ToDecimal to Convert.ToDouble