The following routine is expected to return 1, but instead it returns 0.9999999999999999.
double sum = 0;
for(int i=0; i<10; i++){
sum+=0.1;
}
System.out.println(sum);
The same mistake occurs also with other java mathematical operations.
Is there any way to avoid this issue?
Thank you in advance.
This is what's called a floating point error. It is natural and to be expected. The way to avoid it is to use variables having higher precision, such as BigDecimal
. However BigDecimal
is slower to perform calculations, so consider how important accuracy is important in your solution.
I'd recommend using BigDecimal
despite any performance hits if these quantities represent currency. Its more important your calculation be correct than fast in that case.