C#银行家的舍入误差 [英] C# banker's rounding error

查看:210
本文介绍了C#银行家的舍入误差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

double a = 18.565
return Math.Round(a,2)

..返回18.57。结果
。对于我试图银行家舍和预期一样每隔数,例如Math.Round(2.565,2)返回2.56。

..returns 18.57.
For every other number I tried banker's rounding worked as expected, for example Math.Round(2.565,2) returned 2.56.

任何线索为何以及何时发生这种情况?
它是错误还是我失去了一些关于银行家的舍入?

Any clue why and when that happens? Is it error or am I missing something about banker's rounding?

谢谢..

推荐答案

由于马修说,18.565无法准确表示。使用的实际值是18.565000000000001278976924368180334568023681640625(使用 DoubleConverter ),这显然已经超出了一半。现在,我自以为感觉的有时 Math.Round 将考虑一个值,该值的真正的超越半路点,但作为可以精确地表示,因为恰好是在哪些是尽量靠近中途点的这一点。但是,我还没有看到,描述在其中的应用的情况下的任何文件,并明确它不是在这种情况下发生的。我不想依赖它。

As Matthew said, 18.565 can't be accurately represented. The actual value used is 18.565000000000001278976924368180334568023681640625 (found using DoubleConverter), which is clearly beyond half-way. Now I've a sneaking feeling that sometimes Math.Round will consider a value which is actually beyond the half-way point, but which is as close to the half-way point as can be accurately represented, as being exactly at that point. However, I haven't seen any documentation describing the situations in which that's applied, and clearly it's not happening in this case. I wouldn't want to rely on it.

即使舍入值是不完全的,当然18.57。它实际上18.57000000000000028421709430404007434844970703125。

Even the rounded value isn't exactly 18.57 of course. It's actually 18.57000000000000028421709430404007434844970703125.

从根本上说,如果你真的,真的很在乎准确的代表,你应该使用十进制值的十进制。这不只是在 Math.Round 术语 - 它去处理浮点值的每一个环节。

Fundamentally, if you really, really care about representing decimal values accurately, you should be using decimal. That's not just in terms of Math.Round - it goes to every aspect of handling floating point values.

确实的给予 Math.Round 当然,正确的价值,:

That does give the right value for Math.Round, of course:

decimal m = 18.565m;
Console.WriteLine(Math.Round(m, 2)); // Prints 18.56

这篇关于C#银行家的舍入误差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆