简体   繁体   English

十进制数学舍入

[英]Math.Round for decimal

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. 在这里,我期望输出为2,因为四舍五入到小数点后第一位的1.45将为1.5,下一个四舍五入为小数点后0将为2.45。

However, I am getting the answer as 1. 但是,我得到的答案是1。

Is my assumption correct? 我的假设正确吗? If so, is this a bug with Math.Round? 如果是这样,这是Math.Round的错误吗?

No, it's not a bug. 不,这不是错误。 Your logic talks about rounding twice - but you've only got a single call to Round . 您的逻辑讨论了两次舍入-但是您只有一次调用Round 1.45 is less than the midpoint between 1 and 2 (1.5) so it's rounded down to 1. 1.45小于1和2(1.5)之间的中点,因此四舍五入为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. 除非您指定要舍入两个阶段(如上所述),否则.NET将只执行一个阶段。

You can't do 'round' action one digit by one digit! 您不能一位一位一位地进行“舍入”操作! Here you say: 在这里你说:

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

It's not correct, here 1.45 rounded to 0 digits, you need to check .4 only. 这是不正确的,这里1.45四舍五入为0位数字,您只需要检查.4。

Your understanding is incorrect. 您的理解不正确。

You have specified a decimals value of 0 therefore the value supplied will be rounded to an integer value. 您指定的十进制值为0,因此提供的值将四舍五入为整数值。

From MSDN "If the value of the first digit in d to the right of the decimal position represented by the decimals parameter is 5, the digit in the decimals position is rounded up if it is odd or left alone if it is even" 来自MSDN“如果d中小数点参数表示的小数点位置右边的第一个数字的值是5,则将小数点后的数字四舍五入为奇数,如果为偶数则单独保留”

As the first value to the right of the decimal point is 4 and not five then the value returned is 1. 由于小数点右边的第一个值是4而不是5,因此返回的值是1。

If the decimal value had been 1.55 then the answer would have been 2. 如果十进制值为1.55,则答案为2。

If the decimal value had been 2.55 then the answer would have been 2 as well! 如果十进制值为2.55,那么答案也将为2!

As you are specifying the midpoint rounding behaviour then this will be altered, but you as you are asking the round to work with decimals=0 it will only check the first digit after the decimal point. 当您指定中点舍入行为时,这将被更改,但是当您要求舍入为小数点= 0时,它将仅检查小数点后的第一位。

Infact if you specified decimals=1 as in 如果指定了小数位= 1,则实际上

Math.Round(1.45,1)

Then your answer would be 1.4 as it checks the second digit after the decimal point for rounding of the first. 那么您的答案将是1.4,因为它会检查小数点后的第二个数字是否舍入第一个数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM