简体   繁体   English

将小数点后四舍五入到小数点后两位

[英]Rounding decimal number upto two decimal places

I am trying to round decimal number upto two decimal places which is working perfectly. 我正在尝试将十进制数字四舍五入到小数点后两位,这很正常。 I am doing as below : 我正在做如下:

Math.Round(Amount, 2)

So, if I have Amount as 40000.4567 , I am getting 40000.46 which is exactly what I want. 因此,如果我的金额为40000.4567 ,我得到的40000.46 Now problem is I have decimal number like 40000.0000 , when I round it, the result is 40000 , and what I really want is 40000.00 . 现在的问题是我有一个小数,例如40000.0000 ,当我四舍五入时,结果是40000 ,而我真正想要的是40000.00 So round will always neglect trailing zeros. 因此,回合将始终忽略尾随零。

To solve this problem, I have the option of converting it to string and use format , but I don't want to do that as that will be inefficient and I believe there must be some way to do it better. 为了解决这个问题,我可以选择将其转换为字符串并使用format,但是我不想这样做,因为那样效率低下,我相信必须有一些方法可以更好地做到这一点。

I also tried something like 我也尝试过类似的东西

Decimal.Round(Amount, 2)

Now one way can be to check whether number contains anything in fractional part and use round function accordingly , but that is really bad way to do it. 现在一种方法可以是检查数字是否包含小数部分,并相应地使用舍入函数,但这确实是一种糟糕的方法。 I can't use truncate as well due to obvious reasons of this being related to amount. 由于明显与数量有关的原因,我也不能使用截断。

What is the way around? 怎么回事?

It is rounding correctly but you fail to understand that the value is not the format. 正确的,但四舍五入你不明白, 价值不是格式。 There is no difference between the two values, 40000 and 40000.00 , and you'll have a similar issue with something like 3.1 . 两个值4000040000.00之间没有区别 ,并且类似3.1

Simply use formatting to output whatever number you have to two decimal places, such as with: 只需使用格式将任何数字输出到小数点后两位,例如:

Console.WriteLine(String.Format("{0:0.00}", value));

or: 要么:

Console.WriteLine(value.ToString("0.00"));

You are mixing two things - rounding and output formatting. 您正在混合两件事-舍入和输出格式化。 In order to output a number in a format you want you can use function string.Format with required format, for example: 为了以所需格式输出数字,可以使用函数string.Format和所需格式,例如:

decimal number = 1234.567m;
string.Format("{0:#.00}", number);

You can read more about custom numeric format strings in MSDN 您可以在MSDN中阅读有关自定义数字格式字符串的更多信息

I think what you're looking for is displaying two decimals, even if they are zero. 我认为您正在寻找的是显示两个小数,即使它们是零。 You can use string.Format for this (I've also combined it with Round): 您可以为此使用string.Format(我也将它与Round结合在一起):

Console.WriteLine(string.Format("{0:0.00}", Math.Round(Amount, 2));

for rounding decimal number you can use 舍入十进制数可以使用

decimal number=200.5555m;
number= Math.Round(number, 2);
string numString= string.Format("{0:0.00}", number);

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

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