Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math.Round for decimal

Tags:

c#

rounding

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?

like image 795
Jeevan Avatar asked Jan 22 '23 11:01

Jeevan


1 Answers

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.

like image 68
Jon Skeet Avatar answered Feb 01 '23 02:02

Jon Skeet