Java 模数 1 (%1) returns 近似值

Java Modulus 1 (%1) returns approximate value

我有示例代码

double k=3.14, l=0.5, m=1.3333;
        System.out.println(k+":"+k%1);
        System.out.println(l+":"+l%1);
        System.out.println(m+":"+m%1);

这导致输出:

3.14:0.14000000000000012
0.5:0.5
1.3333:0.33329999999999993

为什么会这样?我期望 x%1 到 return x?

值的非整数部分

Is floating point math broken?

Binary floating point math is like this. In most programming languages, it is based on the IEEE 754 standard. JavaScript uses 64-bit floating point representation, which is the same as Java's double. The crux of the problem is that numbers are represented in this format as a whole number times a power of two; rational numbers (such as 0.1, which is 1/10) whose denominator is not a power of two cannot be exactly represented.