0

When I'm spam clicking on the button it sometimes changes the number of decimals. Why?

<!doctype html>
<html>

<head>

</head>

<body>

<button onmouseover="showSomething()" onmouseout="hideSomething()" onclick="addSomething()">Show something</button>
<p id="show"></p>

<script>

function showSomething() {
 x = Math.random()*100;
 x = x.toFixed(2);
 document.getElementById("show").innerHTML = x;
}

function hideSomething() {
 document.getElementById("show").innerHTML = "";
}

function addSomething() {
 x++;
 document.getElementById("show").innerHTML = x;
}

</script>

</body>

</html>
Cœur
  • 37,241
  • 25
  • 195
  • 267

1 Answers1

0

Should fix your bug.

function addSomething() {
    x++;
    x = x.toFixed(2);
    document.getElementById("show").innerHTML = x;
}
noa-dev
  • 3,561
  • 9
  • 34
  • 72
  • Yea, it probably would, but I don't really care about the bug, I just want to understand why :) – user5097157 Jul 09 '15 at 06:58
  • Because math? You are trying to round up to 2 decimals at the mousenter event but you never do that in the click event. These kind of things can also occur when u are calculating with absolute numbers in any language – noa-dev Jul 09 '15 at 07:00
  • 1
    it's a feature floating point numbers – Jaromanda X Jul 09 '15 at 07:00
  • the problem is explained here: http://programmers.stackexchange.com/questions/101163/what-causes-floating-point-rounding-errors – nowhere Jul 09 '15 at 07:11