# Using double for money is a sin

• 10-14-2008, 08:28 AM
fishtoprecords
Using double for money is a sin
Never use float or double for money or currencies. Use fixed point instead.
Here is a trivial program that shows you how you can not get floating point numbers to add properly.

Changing it from float to double changes where the error occurs, but its still wrong. Testing this is an exercise left to the student.

Code:

```/*  * Copyright (c) 2008, Pat Farrell All rights reserved.  */ package com.pfarrell.utils.math; /**  * The <code>FloatGrok</code> class implements sample code to show how floating point  * numbers don't work the way you expect  *  * @author pfarrell  */ public class FloatGrok { public FloatGrok() { } /**  * do the test  */ public void process() {     float delta = 0.01F;     float sum = 0;     for (int i = 0; i < 100; i++) {         float calc = ((float) i) * delta;         if (sum != calc) {             System.out.printf("i: %d sum: %f != calc: %f\n", i, sum, calc);             break;         }         sum += delta;     } }     /**     * usual shell program entry point     * @param args the command line arguments     */     public static void main(String[] args) {         FloatGrok fg = new FloatGrok();         fg.process();     } }```
• 10-15-2008, 01:29 AM
JDCAce
I have seen some odd stuff with float and double, but I've never heard of fixed point.
• 10-15-2008, 01:46 AM
fishtoprecords
It is well supported in Cobol, but no language that is cool has bothered with it.

Most Java or other languages that deal with this use an implicit fixed point. That is what you get when you use pennies for US currency.
• 11-28-2008, 08:05 AM
fishtoprecords
Here is a nice description of some of the issues. Its from a Python book, but that's fine, the issue is not Java or Python specific, its really a limitation of how float and double are implemented on modern computers.

An Introduction to Python - Floating Point Arithmetic Issues and Limitations