Format of BigDecimal number

前端 未结 4 1966
太阳男子
太阳男子 2020-12-19 20:08
BigDecimal val = BigDecimal.valueOf(0.20);
System.out.println(a);

I want to store in val a value 0.20 and not 0.2. What I

4条回答
  •  独厮守ぢ
    2020-12-19 20:49

    BigDecimal remembers the trailing zeros - with some significant side-effect:

    BigDecimal bd1 = new BigDecimal("0.20"); 
    BigDecimal bd2 = new BigDecimal("0.2");
    
    System.out.println(bd1);
    System.out.println(bd2);
    System.out.println(bd1.equals(bd2));
    

    will print

    0.20
    0.2
    false
    

    And we need to remember, that we can't use BiGDecimal for numbers, where the decimal expansion has a period:

    BigDecimal.ONE.divide(new BigDecimal(3));
    

    will throw an exception (what partially answers your concerns in your comments)

提交回复
热议问题