1

I have something weird going on while adding 0.1 to another number in a loop.

function updateLoop() {
  for (var key in resources) {
    if (resources.hasOwnProperty(key)) { // Key is "Population" here.
      // Add income to stock.
      resources[key][1] += resources[key][0];
      document.getElementById(key).innerHTML = resources[key][1];
    }
  }
  setTimeout(updateLoop, 3000);
}

Now for some reason instead of adding 0.1 it sometimes adds 0.1000000000000001
Inside the resources object:

Population: Array[2]
0: 0.1
1: 1.2000000000000002

Anyone knows why this happens? Can I fix it?

Jonathan
  • 8,771
  • 4
  • 41
  • 78
  • Look into a js decimal library like BigDecimal: https://github.com/iriscouch/bigdecimal.js – jcollum Aug 26 '13 at 21:06
  • Solved it like this though I do worry about performance: `resources[key][1] = (Math.round((resources[key][1] + resources[key][0]) * 10) / 10);` – Jonathan Aug 26 '13 at 21:14
  • Having to put code like that all over the place will get messy. If you need to do it more than a few times a library will save you a lot of effort. – jcollum Aug 26 '13 at 21:17

0 Answers0