Why does below code returns 1299.49 ? According to msdn documentation it should give 1299.5.
Console.WriteLine(Math.Round( 1299.492, 2, MidpointRounding.AwayFromZero))
Why does below code returns 1299.49 ? According to msdn documentation it should give 1299.5.
Console.WriteLine(Math.Round( 1299.492, 2, MidpointRounding.AwayFromZero))
You are rounding to 2 decimal places, hence why 1299.49 is returned.
If you want it to be 1299.5, round to 1 decimal place.
Console.WriteLine(Math.Round( 1299.492, 1, MidpointRounding.AwayFromZero))
From the documentation about AwayFromZero:
When a number is halfway between two others, it is rounded toward the nearest number that is away from zero.
https://msdn.microsoft.com/en-us/library/system.midpointrounding(v=vs.110).aspx
You may be confused as to how this overload works. According to MSDN on MidpointRounding:
When a number is halfway between two others, it is rounded toward the nearest number that is away from zero.
In your case, 1299.492 is not halfway between 1229.49 and 1299.50, so MidpointRounding.AwayFromZero
doesn't even apply.
It looks like what you're actually trying to do is round up to the nearest 2 decimal places. In that case, you want something like this answer:
public static double RoundUp(double input, int places)
{
double multiplier = Math.Pow(10, Convert.ToDouble(places));
return Math.Ceiling(input * multiplier) / multiplier;
}
This rounds up to the specified decimal places by multiplying by 10^places
(100 if you need 2 places), calling Math.Ceiling
, and then dividing.
This works:
Console.WriteLine(RoundUp(1299.492, 2)); // 1299.5