I was trying out subtracting numbers in java, and this gives me unexpected result
public class FloatWeird
{
public static void main(String[] args)
{
double n = 1;
for(int i = 0;i<10;i++)
{
System.out.println(n);
n = n - 0.10;
}
}
}
Result
1.0
0.9
0.8
0.7000000000000001
0.6000000000000001
0.5000000000000001
0.40000000000000013
0.30000000000000016
0.20000000000000015
0.10000000000000014
I have gone through a few forums and understand that using the BigDecimal class is one solution. However, is there a way to correct it in a simpler way using double as above?
I suggest you use appropriate rounding.
When ever you print a double you have to consider what the appropriate round is.
You can also round the result as you calculate which is what BigDecimal does.
This will reduce cumulative error.
Another approach is to work in a different unit, e.g. instead of dollar you use cents. This means you can use an
intorlongand only convert to dollars for presentation.this prints http://ideone.com/Uf70jC
Note: even if you use BigDecimal, this still have to do this except the API can help you determine at what point you should do this.