floats and doubles

When you’re doing *really* precise maths with large numbers (for that you can read currency conversions), Java floats do not necessarily do what you might expect. I’ve just wasted half a day tracking down a rounding error for a calculation that was 3 cents out for numbers over 7 million. It’s a small triumph but one I’ll take gladly at the moment. In the end I just switched to use doubles instead and they work as I’d expect (which I guess may not actually be correct but they do at least match Excel and my calculator!).

Join the Conversation

1 Comments

  1. Unless you have some serious performance reasons why not, I’d always go with java.math.BigDecimal for financial calcs. That way you are pretty much guaranteed to get the correct value.You can get wrong answers really easily using simple floats. And it’s not really a Java specific thing, anything that implements the IEEE 754 specification just isn’t going to work as you might expect in all sorts of situations. For example you just can’t store 0.1 accurately as a float or double. The best you can hope for is that the precision you want is course grained enough that the true value will round up to what you want.<img alt="Emoticon" src="http://www.11tmr.com/11tmr.nsf/emoticons/DLYH-5N3GL7/$File/undecided.gif“ />

    Like

Leave a comment