This question already has an answer here:
这个问题在这里已有答案:
- Java:Why should we use BigDecimal instead of Double in the real world? [duplicate] 6 answers
Java:为什么我们应该在现实世界中使用BigDecimal而不是Double? [重复] 6个答案
I have a silly question. Why this is giving 488.15999999999997 instead of 488.16
我有一个愚蠢的问题。为什么这给了488.15999999999997而不是488.16
double dbl = 427.14 + 61.02;
System.out.println(dbl);
I heard that we must use BigDecimal if we are considering this much accuracy (like currency related logics). But I want to know what is behind this.
我听说如果我们考虑这么高的准确性(如货币相关逻辑),我们必须使用BigDecimal。但我想知道这背后是什么。
2 个解决方案
#1
1
It's "normal" behavior. Remember, for the general case decimal values can not be represented exactly in a computer, so little errors will begin to creep. Take a look at What Every Computer Scientist Should Know About Floating-Point Arithmetic, it's mandatory reading for anyone writing code dealing with decimal values.
这是“正常”行为。请记住,对于一般情况,十进制值无法在计算机中准确表示,因此很少有错误会开始蔓延。看看每个计算机科学家应该知道的关于浮点运算的内容,对于任何编写处理十进制值的代码的人来说,它都是必读的。
#2
1
How to resolve a Java Rounding Double issue This similar question's answer points here https://blogs.oracle.com/CoreJavaTechTips/entry/the_need_for_bigdecimal
如何解决Java Rounding Double问题这个类似问题的答案点在这里https://blogs.oracle.com/CoreJavaTechTips/entry/the_need_for_bigdecimal
#1
1
It's "normal" behavior. Remember, for the general case decimal values can not be represented exactly in a computer, so little errors will begin to creep. Take a look at What Every Computer Scientist Should Know About Floating-Point Arithmetic, it's mandatory reading for anyone writing code dealing with decimal values.
这是“正常”行为。请记住,对于一般情况,十进制值无法在计算机中准确表示,因此很少有错误会开始蔓延。看看每个计算机科学家应该知道的关于浮点运算的内容,对于任何编写处理十进制值的代码的人来说,它都是必读的。
#2
1
How to resolve a Java Rounding Double issue This similar question's answer points here https://blogs.oracle.com/CoreJavaTechTips/entry/the_need_for_bigdecimal
如何解决Java Rounding Double问题这个类似问题的答案点在这里https://blogs.oracle.com/CoreJavaTechTips/entry/the_need_for_bigdecimal