舍入十进制值 [英] Rounding decimal value
问题描述
Math.Round(a,2);
<当我用1.2小数点后两位数舍入时,结果是1.27。
当我做同样的1.375时,结果是1.38。
为什么不是四舍五入的1.275到1.28?
谢谢
我不能重现您的问题:
Math.Round(1.275m,2)=> 1.28m
Math.Round(1.375m,2)=> 1.38m
我怀疑你声称你使用 decimal
值为false,而您使用 double
值来代替。 double
不能完全表示很多十进制值,所以当你写 1.275
时,实际上是1.27499 ... 1.375
是少数可表示的元素之一,所以它实际上是 1.375
。
如果您的代码关心精确的十进制表示,例如在处理金钱时,您必须使用 decimal
,而不是二进制浮点数如 double
或 float
。
但是即使使用十进制表示法,对于许多用户来说,四舍五入也会出乎意料:
$ b $ pre $ Math.Round 1.265m,2)=> 1.26m
Math.Round(1.275m,2)=> 1.28m
默认 Math.Round
使用 MidpointRounding.ToEven
,也称为银行家轮。这样可以避免在 .5
之间累积偏差。
您可以使用 Round
,它采用舍入模式,并将其设置为 AwayFromZero
以获得您期望的行为
Math.Round(1.275m,2,MidpointRounding.AwayFromZero)=> 1.28m
I am facing problem while rounding the decimal value in C# using Math.Round(a, 2);
When I'm rounding 1.275 by 2 decimal points, the result is 1.27. When I'm doing the same for 1.375, the result is 1.38.
Why is it not rounding 1.275 to 1.28?
Thanks
I cannot reproduce your problem:
Math.Round(1.275m, 2) => 1.28m
Math.Round(1.375m, 2) => 1.38m
I suspect that your claim that you use a decimal
value is false, and that you use double
value instead. double
can't represent many decimal values exactly, so when you write 1.275
, it's actually 1.27499... 1.375
is one of the few representable onces, so it's actually 1.375
.
If your code cares about exact decimal representation, for example when you work on money, you must use decimal
and not binary floating point such as double
or float
.
But even if you use decimal representation, rounding behaves unexpectedly for many users:
Math.Round(1.265m, 2) => 1.26m
Math.Round(1.275m, 2) => 1.28m
By default Math.Round
uses MidpointRounding.ToEven
, also known as Banker's round. This avoids accumulating a bias from always rounding up at .5
.
You can use an overload of Round
that takes a rounding mode, and set it to AwayFromZero
to get the behaviour you expect.
Math.Round(1.275m, 2, MidpointRounding.AwayFromZero) => 1.28m
这篇关于舍入十进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!