Search code examples
javafloating-pointdoubleprecision

Formatting doubles with highest possible precision


A number such as 0.1 cannot be precisely represented using binary floating point, so I want to print it out with the highest possible precision. I know that the 64-bit double type only gives meaningful precision up to about 15 digits, but further digits would reveal the difference between the floating-point approximation and the real value.

However, a format with high precision specification such as "%.50f" still doesn't give me it:

String.format("%.50f", 0.1)    --> "0.10000000000000000000000000000000000000000000000000"
new BigDecimal(0.1).toString() --> "0.1000000000000000055511151231257827021181583404541015625"

Is there any way to output the number as a string without using BigDecimal?


Solution

  • As the last meaningful digit might be either rounded up or down, one cannot just glue 00...00 (99...99) after it.

    So as there still is an approximation error after some 15 odd digits, new BigDecimal("...") is the appropriate solution. You could assume that the actual precision is 14 or lower and then add zeroes. But still printf/format gives fake news.