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 number in string for example:
for
BigDecimal bd = new BigDecimal(10.0001)
System.out.println(bd.toString());
System.out.println(bd.toPlainString());
the output is:
10.000099999999999766941982670687139034271240234375
10.000099999999999766941982670687139034271240234375
and i need the out put to be exactly the number 10.0001 in string
To get exactly
10.0001you need to use the String constructor orvalueOf(which constructs a BigDecimal based on the canonical representation of the double):The problem with
new BigDecimal(10.0001)is that the argument is adoubleand it happens that doubles can’t represent10.0001exactly. So10.0001is “transformed” to the closest possible double, which is10.000099999999999766941982670687139034271240234375and that’s what yourBigDecimalshows.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