Reputation: 33
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"
Upvotes: 3
Views: 11687
Reputation: 1384
As far as I understood, you want to print the number in special format. You need to call applyPattern(String Pattern) as here:
f.applyPattern(".000");
System.out.println(f.format(123456789.99)); // prints 123456789.990
Note patterns are localised, e.g. in Germany it will print , instead of . to separate the fraction. You can set the rounding preferrence via
f.setRoundingMode()
Guess where did I learn all this? of course from Java docs. Read more about the pattern expression to format the way you like
Upvotes: 1
Reputation: 533520
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
Upvotes: 5
Reputation: 308763
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".
Upvotes: 1