Java. How to disable rounding in DecimalFormat

skif picture skif · Feb 7, 2011 · Viewed 10.1k times · Source

Can I disable rounding "feature" in DecimalFormat?

For example:

DecimalFormat f = new DecimalFormat();

f.parseObject("123456789012345.99");

Result is 1.2345678901234598E14

java version "1.6.0_21"

Answer

Peter Lawrey picture Peter Lawrey · Feb 7, 2011

This is nothing to do with a feature of Java. It is due to the limited precision of IEEE 64-bit double floating numbers. In fact all data types have limits to their precision. SOme are larger than others.

double d = 123456789012345.99;
System.out.println(d);

prints

1.2345678901234598E14

If you want more precision use BigDecimal.

BigDecimal bd = new BigDecimal("123456789012345.99");
System.out.println(bd);

prints

123456789012345.99

Even BigDecimal has limits too, but they are far beyond what you or just about any one else would need. (~ 2 billion digits)

EDIT: The largest known primes fit into BigDecimal http://primes.utm.edu/largest.html