小数精度 [英] Accuracy of decimal

查看:58
本文介绍了小数精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用十进制类型进行高精度计算(货币).

I use the decimal type for high precise calculation (monetary).

但是我今天遇到了这个简单的部门:

But I came across this simple division today:

1//(1/37)应该会再次导致37

1 / (1 / 37) which should result in 37 again

http://www.wolframalpha.com/input/?i = 1%2F +%281%2F37%29

但是C#给了我: 37.000000000000000000000000037M

我尝试了这两种方法: 1m/(1m/37m); Decimal.Divide(1,Decimal.Divide(1,37))

I tried both these: 1m/(1m/37m); and Decimal.Divide(1, Decimal.Divide(1, 37))

,但两者产生相同的结果.行为如何解释?

but both yield the same results. How is the behaviour explainable?

推荐答案

Decimal 将值存储为十进制浮点数,但精度有限.1/37的结果未正确存储,因为它存储为0.027027027027027027027027027M.真实数字的组027以十进制表示形式无限期地前进.因此,您无法获得每个可能数字的精确数字(以十进制表示).

Decimal stores the value as decimal floating point with only limited precision. The result of 1 / 37 is not precicely stored, as it's stored as 0.027027027027027027027027027M. The true number has the group 027 going indefinitely in decimal representation. For that reason, you cannot get the precise numbers in decimal representation for every possible number.

如果在同一计算中使用 Double ,则最终结果在这种情况下是正确的(但这并不意味着它将总是更好).

If you use Double in the same calculation, the end result is correct in this case (but it does not mean it will always be better).

关于该主题的一个很好的答案是在这里:

A good answer on that topic is here: Difference between decimal, float and double in .NET?

这篇关于小数精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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