Unpredictability of the BigDecimal(double) constructor

前端 未结 6 2186
后悔当初
后悔当初 2020-12-01 18:27

I started using Sonar recently in a project, and i got a PMD rule broken about using the constructor new BigDecimal(double val). When i read the java documentat

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 18:46

    Why does this constructor really exists?

    It converts the actual represented value of double to a BigDecimal. The whole point of BigDecimal is to give as much precision as possible and that is what this constructor does.

    If you want to take the value you would get with a small amount of rounding the Double.toString(double) uses you can use

    System.out.println(BigDecimal.valueOf(0.1));
    

    prints

    0.1
    

    When should I use the new BigDecimal(double val) constructor

    When you want to know the value double really represents. You can apply your own rounding as required.

    When you use double you should always apply a sensible rounding. But, if you did that you may find you don't need BigDecimal. ;)

提交回复
热议问题