Search code examples
doublebigdecimal

java double to BigDecimal convertion adding extra trailing zero


double d =0.0000001;
BigDecimal d1 = BigDecimal.valueOf(d);
System.out.println(d1.toPlainString());

prints output => 0.00000010 i am expecting 0.0000001


Solution

  • First, to get a precise BigDecimal value, avoid using a float or double to initialize it. The conversion from text to floating point type is by definition not guaranteed to be precise. The conversion from such a type to BigDecimal is precise, but may not exactly yield the result you expected.

    If you can avoid using a double or float for initialization, then do something like this instead:

    BigDecimal d = new BigDecimal("0.0000001");
    

    This will already give you the desired output, because the conversion from (decimal) text to BigDecimal is precise.

    But if you really must convert from a double, then try:

    double d = 0.0000001;
    BigDecimal d1 = BigDecimal.valueOf(d);
    System.out.println(d1.stripTrailingZeros().toPlainString());
    

    This will strip (remove) any trailing zeroes.