Format of BigDecimal number

前端 未结 4 1975
太阳男子
太阳男子 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:56

    You're passing a double to BigDecimal.valueOf(). And 0.20 is exactly the same double as 0.2. Pass it a String, and the result will be different, because the scale of the BigDecimal will be deduced from the number of decimals in the String:

    BigDecimal bd1 = new BigDecimal("0.20");
    BigDecimal bd2 = new BigDecimal("0.2");
    
    System.out.println(bd1.toPlainString() + ", scale = " + bd1.scale()); // 0.20, scale = 2
    System.out.println(bd2.toPlainString() + ", scale = " + bd2.scale()); // 0.2, scale = 1
    
    NumberFormat nf = NumberFormat.getInstance();
    
    nf.setMinimumFractionDigits(bd1.scale());
    System.out.println(nf.format(bd1)); // 0,20 (in French locale)
    
    nf.setMinimumFractionDigits(bd2.scale());
    System.out.println(nf.format(bd2)); // 0,2 (in French locale)
    

提交回复
热议问题