简体   繁体   English

Math.Round(double,2)返回1个小数

[英]Math.Round(double,2) returns 1 decimal

Why does this code returns 1 decimal instead of 2 为什么此代码返回1 decimal而不是2 decimal

p = Math.Round(9431.796, 2);

If I replace this with p = Math.Round(9431.796, 4); 如果我将其替换为p = Math.Round(9431.796, 4); It still returns 1 decimal 它仍然返回1 decimal

If you round 9431.796 to two decimal places, you will get 9431.80 . 如果将9431.796到小数点后两位,将得到9431.80

Numerical data types don't store actual digits. 数字数据类型不存储实际数字。 They store a representation of a number. 它们存储数字的表示形式。 9431.80 is exactly the same number as 9431.8 , and there will be no distinction made between them when they are stored in a decimal or double variable. 9431.809431.80完全相同,并且将它们存储在decimaldouble 9431.8变量中时,它们之间没有区别。

So if you display 9431.80 without doing anything to format it a certain way, it will display as 9431.8 . 因此,如果您显示9431.80而不进行任何格式化操作,它将显示为9431.8 So the problem is with your understanding of how numbers are stored in numerical datatypes. 因此,问题在于您对数字如何存储在数字数据类型中的理解。

You create a string with a certain number of decimal places by using .ToString() . 通过使用.ToString()创建具有一定小数位数的字符串。 You don't need to use Math.Round() in this case. 在这种情况下,您不需要使用Math.Round() .ToString() will round it: .ToString()将四舍五入:

var p = 9431.796.ToString("0.00");
Console.WriteLine(p);                // 9431.80

You cannot because 9431.80 is equal to 9431.8. 您不能因为9431.80等于9431.8。 In this case however I guess that you want to print it out with specific format, which can be done like this: 但是,在这种情况下,我想您想使用特定格式将其打印出来,可以这样进行:

string p = Math.Round(9431.796, 2).ToString("0.00");

Math.Round(9431.796, 2) returns one decimal becauses it rounds to 9431.80. Math.Round(9431.796, 2)返回一个小数,因为它舍入到9431.80。 When displayed, it gets rid of the last 0, that's why you only see one decimal. 显示时,它会删除最后一个0,这就是为什么您只看到一个小数的原因。
Math.Round(9431.796, 4) should definitely return 9431.796. Math.Round(9431.796, 4)肯定会返回9431.796。 Could you test it again? 您可以再测试一次吗?

Since it rounds to 9431.80 it delete the last 0 which is useless. 由于它9431.809431.80因此删除了最后一个无效的0 I would use : 我会使用:

int nbDec = 2;
p = Math.Round(9431.796, nbDec );
Console.Out.WriteLine(p.ToString("#,##0." + new string('#',nbDec ));

Which will display 9,431.80 . 这将显示9,431.80

If you want more or less decimal, just change the nbDec value. 如果您想要更多或更少的小数,只需更改nbDec值即可。

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

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