Please ! Stop using floating point numbers for financial data

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…

About these ads

2 thoughts on “Please ! Stop using floating point numbers for financial data

  1. 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) 
    

    :)

    • 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