Math.Round for decimal

I run this code:

decimal d = 1.45M;

Console.WriteLine((System.Math.Round(d,0,MidpointRounding.AwayFromZero).ToString()));

Here I expect the result to be 2, since 1.45 when rounding to the 1st decimal place will be equal to 1.5, when the next rounding to 0 decimal places should be 2.

However, I get the answer as 1.

Is my assumption correct? If so, is this a bug with Math.Round?

+3
source share
3 answers

No, this is not a mistake. Your logic says rounding twice, but you only have one call Round. 1.45 is less than the middle between 1 and 2 (1.5), therefore it is rounded to 1.

If you want the code to fit 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);
    }
}

, ( ),.NET .

+8

"" ! :

1.45 rounded to 1 decimal place:1.5
1.5 rounded to 0 decimal place:2

, 1.45 0 , .4.

0

.

0, .

MSDN " d , , 5, , ​​ , "

4, , 1.

1,55, 2.

2.55, 2!

When you specify the rounding behavior in the middle, it will change, but you, since you ask the round to work with decimals = 0, it only checks the first digit after the decimal point.

Infact if you specified decimals = 1, as in

Math.Round(1.45,1)

Then your answer will be 1.4, as it checks the second digit after the decimal point to round the first.

0
source

Source: https://habr.com/ru/post/1763408/


All Articles