Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java. How to disable rounding in DecimalFormat

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"

like image 886
skif Avatar asked Mar 22 '26 16:03

skif


2 Answers

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

like image 156
Peter Lawrey Avatar answered Mar 25 '26 06:03

Peter Lawrey


No, that's not rounding, that's just the way floating point numbers work.

The only way to do what you want is to use BigDecimal.

I'd recommend that you read "What Every Computer Scientist Should Know About Floating Point Arithmetic".

like image 41
duffymo Avatar answered Mar 25 '26 04:03

duffymo