Objectopia

Please ! Stop using floating point numbers for financial data

Posted by Chris Burnley on July 3, 2009

Again and again I see developers using doubles for storing financial data (e.g. monetary figures, interest rates etc.). This always causes some sort of rounding issue down the line.

try this in your IDE:

double total = 0;
for (int i =0; i <  10; i++){
  total += 0.1;
}
System.out.println(total);

If you expect the answer to be 1 or 1.0, then you’re wrong !

Question: are you writing a game ? Answer: no; then use an effing BigDecimal!

Grrr…

2 Responses to “Please ! Stop using floating point numbers for financial data”

  1. Jon Court said

    But, before you go creating BigDecimals from doubles all over the place be sure to read the javadoc here.

    In summary – you would generally use:

    BigDecimal.valueOf(double) 
    

    rather than:

    new BigDecimal(double) 
    

    :)

    • Chris Burnley said

      The point is: don’t use them, ever if you can avoid it. The are only approximations. All input should be captured directly into bigdecimals.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.