我使用十进制类型进行高精度计算(货币).
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
www.wolframalpha/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).
关于该主题的一个很好的答案是在这里: .NET中小数,浮点数和双精度之间的区别?
A good answer on that topic is here: Difference between decimal, float and double in .NET?
更多推荐
小数精度
发布评论