问题描述
我正在尝试将十进制数四舍五入到小数点后两位,这非常有效.我正在做如下:
I am trying to round decimal number upto two decimal places which is working perfectly.I am doing as below :
Math.Round(Amount, 2)
因此,如果我的金额为 40000.4567
,我会得到 40000.46
,这正是我想要的.现在的问题是我有一个十进制数字,如 40000.0000
,当我四舍五入时,结果是 40000
,而我真正想要的是 40000.00
.因此,回合将始终忽略尾随零.
So, if I have Amount as 40000.4567
, I am getting 40000.46
which is exactly what I want.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
. So round will always neglect trailing zeros.
要解决此问题,我可以选择将其转换为字符串并使用format,但是我不想这样做,因为这样做效率不高,我相信必须有一些方法可以更好地做到这一点.
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.
我也尝试过
Decimal.Round(Amount, 2)
现在一种方法是检查数字是否包含小数部分并相应地使用round函数,但这确实是一种糟糕的方法.由于明显与数量有关的原因,我也不能使用truncate.
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.
怎么回事?
推荐答案
是正确舍入,但是您无法理解 value 不是格式.两个值 40000
和 40000.00
之间没有差异,并且类似的问题也会出现 3.1
.
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
.
只需使用格式将任意数字输出到小数点后两位,例如:
Simply use formatting to output whatever number you have to two decimal places, such as with:
Console.WriteLine(String.Format("{0:0.00}", value));
或:
Console.WriteLine(value.ToString("0.00"));
这篇关于将小数点后四舍五入到小数点后两位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!