Ventrix’s Code Folds

Java float problems

by ventrix on Dec.23, 2008, under android, j2ee, j2se, java

If you want 0.6917 - 0.6911 to be 0.0006 then:

http://www.velocityreviews.com/forums/showpost.php?s=bfd8bcba71b3b530733952c65e86772a&p=1604265&postcount=4

There are three solutions:

1. If you’ve got enough accuracy but just need the numbers to look
better when you display them, then you can simply use
java.text.DecimalFormat to format the answers to a more reasonable
length when they are displayed. Rounding will occur as appropriate in
the display layer, and the result should look just fine.

2. If you aren’t getting enough precision, then you could look into the
double data type instead of float. Double has not only an immensely
larger range, but also approximately twice the precision in digits.

3. If you need exact math in decimal (often required for financial
calculations, for example) then the class java.math.BigDecimal is what
you’re looking for. BigDecimal lets you store values of any arbitrary
precision; it stores them in decimal, so you need not worry about
rounding that results from binary conversion, and you can customize the
rounding mode on operations that still need it, like division… or even
disabling rounding entirely so that the runtime will throw an exception
to let you know when a calculation won’t have an exact result.

:,
No comments for this entry yet...

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...

Archives

All entries, chronologically...