0

The following code generates numbers and than divides it with 1000: But some times numbers like 1.2295999999999998 are generated, while 1229.6 is only being divided by 1000?

What do I need to change in the code, so that this does not occur?

Z1 = document.getElementById("Z1").innerHTML = Math.floor((Math.random() * 99899 + 100)) / Math.pow(10, Math.floor((Math.random() * 3 + 1)));

document.getElementById("L").innerHTML = Z1 / 1000;
<label id="Z1"></label><br>
<label id="L"></label>
Save Pain
  • 247
  • 2
  • 9

1 Answers1

0
document.getElementById("L").innerHTML = (Z1 / 1000).toFixed(2); 
// if you want 2 digits after decimalpoint

Further Explaination:

Floating point numbers cannot represent all decimals precisely in binary. It has to do with how decimal values are converted to binary floating point numbers. For example, 1/10 turns into a repeating decimal in binary, so the number is not perfectly represented, and repeated operations can expose the error.

KienHT
  • 1,098
  • 7
  • 11