Unpredictability of the BigDecimal(double) constructor

前端 未结 6 2207
后悔当初
后悔当初 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:43

    double val = 0.1; // this is not 0.1, but an approximination as pointed out in other answers.
    BigDecimal biggy = new BigDecimal(val); // this variable conatains the "same" value as val does, however it is not 0.1, but as pointed out in other answers: 0.100000000000000005551115123`
    

    So, in the case listed here, where you have full control over the source code, you should write the val as 'String val = "0.1"'

    However the contructor BigDecimal(double val) is usefull in case you read binary doubles from a file. Obviously you will want in nearly all cases BigDecimals that are exactly the same as the 'doubles'

提交回复
热议问题