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.
/*
* 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();
}
}