Floating point operations such like this aren't precise; this is a well-known problem in computer science. See also: https://floating-point-gui.de/basic/
It's basically the same problem as if someone asks you to give a precise answer to "What's 1 divided by 3, to 10 decimal places?" - the best answer you could give is 0.3333333334.
But 3 * 0.3333333334 = 1.0000000002
It's a limitation that exists in every number system, just in different cases.
If you need exact numbers, you should use BigDecimal:
import java.math.BigDecimal;
class FloatingPointExample {
public static void main(String[] args) {
// Prints 7.6000004
System.out.println(8.6f - 1.0f);
// Prints 7.6
System.out.println(new BigDecimal("8.6").subtract(new BigDecimal("1.0")));
// Do NOT pass floats to BigDecimal
// Prints 7.6000003814697265625
System.out.println(new BigDecimal(8.6f).subtract(new BigDecimal(1.0f)));
// Do NOT pass doubles to BigDecimal
// Prints 7.5999999999999996447286321199499070644378662109375
System.out.println(new BigDecimal(8.6).subtract(new BigDecimal(1.0)));
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…