BigDecimal to string

Solution 1:

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

Solution 2:

Your BigDecimal doesn't contain the number 10.0001, because you initialized it with a double, and the double didn't quite contain the number you thought it did. (This is the whole point of BigDecimal.)

If you use the string-based constructor instead:

BigDecimal bd = new BigDecimal("10.0001");

...then it will actually contain the number you expect.

Solution 3:

For better support different locales use this way:

DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(0);
df.setGroupingUsed(false);

df.format(bigDecimal);

also you can customize it:

DecimalFormat df = new DecimalFormat("###,###,###");
df.format(bigDecimal);

Solution 4:

By using below method you can convert java.math.BigDecimal to String.

   BigDecimal bigDecimal = new BigDecimal("10.0001");
   String bigDecimalString = String.valueOf(bigDecimal.doubleValue());
   System.out.println("bigDecimal value in String: "+bigDecimalString);

Output:
bigDecimal value in String: 10.0001

Solution 5:

// Convert BigDecimal number To String by using below method //

public static String RemoveTrailingZeros(BigDecimal tempDecimal)
{
    tempDecimal = tempDecimal.stripTrailingZeros();
    String tempString = tempDecimal.toPlainString();
    return tempString;
}

// Recall RemoveTrailingZeros
BigDecimal output = new BigDecimal(0);
String str = RemoveTrailingZeros(output);