0

I've got sample code

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);

which results in output:

3.14:0.14000000000000012
0.5:0.5
1.3333:0.33329999999999993

Why is it so? I expected x%1 to return non-integer part of the value of x?

Jim Morr
  • 3
  • 8
  • 4
    Floating point values aren't precise. Rounding errors always need to be accounted for after any operation. – CollinD Nov 11 '16 at 07:06
  • `0.14` and `0.3333` can't be represented exactly, that's why there are rounding errors. `0.5` on the other hand can be represented exactly. – QBrute Nov 11 '16 at 07:07
  • http://www.adambeneschan.com/How-Does-Floating-Point-Work/showfloat.php?floatvalue=3.14&floattype=double – ajb Nov 11 '16 at 07:20

1 Answers1

1

See 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.

Community
  • 1
  • 1
KC Wong
  • 2,410
  • 1
  • 18
  • 26