舍入十进制值

编程入门 行业动态 更新时间:2024-10-26 14:31:03
本文介绍了舍入十进制值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 使用 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

更多推荐

舍入十进制值

本文发布于:2023-06-02 07:33:19,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:舍入十进制值

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!