I am trying to round my values so that if it's 0.5
or greater, it becomes 1
, else it becomes 0
. For example:
3.7 -> 4;
1.3 -> 1;
2.5 -> 3;
...
Any ideas?
I am trying to round my values so that if it's 0.5
or greater, it becomes 1
, else it becomes 0
. For example:
3.7 -> 4;
1.3 -> 1;
2.5 -> 3;
...
Any ideas?
Math.Round(3.7,MidpointRounding.AwayFromZero);
http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx
In the above, I made use of AwayFromZero
for rounding because the default is Banker's rounding, so if the fraction is 0.5, it is rounded to nearest even. So 3.5 becomes 4 (nearest even), but 2.5 becomes 2 (nearest even). So you choose a different method as shown above to make 3.5 to 4 and 2.5 to 3.
I arrived last, so I'll tell something different. You round 0.5
to 1
by not using double
! Use decimal
s. double
aren't good to have "exact" numbers.
Launch this piece of code and have fun (note that there is/was a "bug" in mono on numbers like 0.49999999999999994, so to run it on ideone I had to modify it a little to try to round 1.5: http://ideone.com/57XAYV)
public static void Main()
{
double d = 1.0;
d -= 0.3;
d -= 0.2;
Console.WriteLine("Standard formatting: {0}", d); // 0.5
Console.WriteLine("Internal Representation: {0:r}", d); // 0.49999999999999994
Console.WriteLine("Console WriteLine 0 decimals: {0:0}", d); // 1
Console.WriteLine("0 decimals Math.Round: {0}", Math.Round(d, MidpointRounding.AwayFromZero)); // 0
Console.WriteLine("15 decimals then 0 decimals Math.Round: {0}", Math.Round(Math.Round(d, 15, MidpointRounding.AwayFromZero), MidpointRounding.AwayFromZero)); // 1
}
Round-Up
Math.Round(3.5, 0, MidpointRounding.AwayFromZero) -> 4
Round Down
Math.Round(3.5, 0, MidpointRounding.ToEven) -> 3