Double subtraction precision issue

后端 未结 5 2142
余生分开走
余生分开走 2020-12-05 04:49

My coworker did this experiment:

public class DoubleDemo {

      public static void main(String[] args) {
           double a = 1.435;
           double b =         


        
5条回答
  •  执笔经年
    2020-12-05 05:31

    double is internally stored as a fraction in binary -- like 1/4 + 1/8 + 1/16 + ...

    The value 0.005 -- or the value 1.435 -- cannot be stored as an exact fraction in binary, so double cannot store the exact value 0.005, and the subtracted value isn't quite exact.

    If you care about precise decimal arithmetic, use BigDecimal.

    You may also find this article useful reading.

提交回复
热议问题