0

Eclipse gives the wrong result when trying to calculate the sum of two floats. In my code, there are 2 float variables: float from = 0.025 and float to = 1. Then result has double variable: double value = 7 * from / to. Eclipse compiler shows: value = 0.174999997019767760 In excel calculator, this result was value = 0.175

How can I solve this an issue?

Will_Panda
  • 534
  • 10
  • 26

1 Answers1

0

This is simply due to your Java program not rounding the result the same way the excel calculator does. This is a result of the way computers handle floating point arithmetic. You have two options: round the result, or use the java BigDecimal class. If you want to round the result, you can use:

float from = 0.025f;
float to = 1;
double value = 7 * from / to;
DecimalFormat ds = new DecimalFormat("#.###");
double rounded = Double.parseDouble(ds.format(value));
System.out.println(rounded);

If you would rather not have to round, you can use the BigDecimal class. Java BigDecimal

JPadley
  • 333
  • 2
  • 4
  • 20