Retain precision with double in Java

前端 未结 22 3082
情歌与酒
情歌与酒 2020-11-21 05:15
public class doublePrecision {
    public static void main(String[] args) {

        double total = 0;
        total += 5.6;
        total += 5.8;
        System.out         


        
22条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-21 06:07

    Short answer: Always use BigDecimal and make sure you are using the constructor with String argument, not the double one.

    Back to your example, the following code will print 11.4, as you wish.

    public class doublePrecision {
        public static void main(String[] args) {
          BigDecimal total = new BigDecimal("0");
          total = total.add(new BigDecimal("5.6"));
          total = total.add(new BigDecimal("5.8"));
          System.out.println(total);
        }
    }
    

提交回复
热议问题