Unexpected decimal result

你说的曾经没有我的故事 提交于 2019-12-12 15:14:12

问题


I run the following code, but did not expect that result..

public class SampleDemo {
    public static void main(String args[]) {  
        System.out.println(10.00 - 9.10);
    }
}

I am getting o/p as 0.9000000000000004

Why is it so?


回答1:


This is because decimal values can’t be represented exactly by float or double.

One suggestion : Avoid float and double where exact answers are required. Use BigDecimal, int, or long instead


Using int :

public class SampleDemo {
    public static void main(String args[]) {  
        System.out.println(10 - 9);
    }
}

// Output : 1

Using BigDecimal :

import java.math.BigDecimal;

public class SampleDemo {
  public static void main(String args[]) {
     System.out.println(new BigDecimal("10.00").subtract(new BigDecimal("9.10")));
                             }
                     }
// Output : 0.90


来源:https://stackoverflow.com/questions/6075422/unexpected-decimal-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!