BigDecimal to string

后端 未结 8 1746
感情败类
感情败类 2020-12-13 08:06

I have a BigDecimal object and i want to convert it to string. The problem is that my value got fraction and i get a huge number (in length) and i only need the original num

8条回答
  •  既然无缘
    2020-12-13 08:50

    To get exactly 10.0001 you need to use the String constructor or valueOf (which constructs a BigDecimal based on the canonical representation of the double):

    BigDecimal bd = new BigDecimal("10.0001");
    System.out.println(bd.toString()); // prints 10.0001
    //or alternatively
    BigDecimal bd = BigDecimal.valueOf(10.0001);
    System.out.println(bd.toString()); // prints 10.0001
    

    The problem with new BigDecimal(10.0001) is that the argument is a double and it happens that doubles can't represent 10.0001 exactly. So 10.0001 is "transformed" to the closest possible double, which is 10.000099999999999766941982670687139034271240234375 and that's what your BigDecimal shows.

    For that reason, it rarely makes sense to use the double constructor.

    You can read more about it here, Moving decimal places over in a double

提交回复
热议问题