I am running this code:
decimal d = 1.45M;
Console.WriteLine((System.Math.Round(d,0,MidpointRounding.AwayFromZero).ToString()));
Here I expect the output to be 2 because 1.45 when rounded to 1st decimal place will be 1.5 which when next rounded to 0 decimal places should be 2.
However, I am getting the answer as 1.
Is my assumption correct? If so, is this a bug with Math.Round?
No, it's not a bug. Your logic talks about rounding twice - but you've only got a single call to Round
. 1.45 is less than the midpoint between 1 and 2 (1.5) so it's rounded down to 1.
If you want the code to follow your logic, you can do this:
using System;
class Test
{
static void Main()
{
decimal d = 1.45m;
d = Math.Round(d, 1, MidpointRounding.AwayFromZero); // 1.5
d = Math.Round(d, 0, MidpointRounding.AwayFromZero); // 2
Console.WriteLine(d);
}
}
Unless you specify that you want two phases of rounding though (as above) .NET will just do the one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With