Search code examples
javastringdoubleconvertersbigdecimal

When is there "data loss" when converting from BigDecimal to Double in Java


I know there are "precision issues" when converting BigDecimal values to Double in Java. When is there "data loss" when simply converting from BigDecimal to Double using BigDecimal.doubleValue()? For example, if I convert 1.1 from BigDecimal to Double and print it out, it prints "1.1" which I would consider to have no data loss (the BigDecimal was 1.1 and the printed value was 1.1). When are the cases these two values would not be the same when simply converting from BigDecimal to Double in this way?


Solution

  • BigDecimal has as much precision as you like. A double has 53 bits of binary precision, which is ~15.9 decimal digits. So any time your BigDecimal has > 16 significant digits you are in for loss of precision when converting to double.

    [This is in reference to integer values. The situation with fractions is considerably more complex, but the fact remains that BigDecimal has unlimited precision where double does not.]

    Also a double has minimum and maximum values, given by Double.MIN_VALUE/MAX_VALUE. BigDecimal has neither.