-1

I want to create a simple counter in Javascript and I have a snippet for it already. The issue is, I would also like for the counter's value to increase by a value of decimals. If I simply use, for instance, the value of "0.13" as increment, the result I often get is: "0.230000000013" instead of simply "0,23". I read that it may be fixed by applying the rounding to the result (n * 100 )/100), but I was not able to implement it correctly.

My code is, as below:

var START_DATE = new Date("October 27, 2015 16:30:00"); // put in the starting date here
var INTERVAL = 1; // in seconds
var INCREMENT = 0.13; // increase per tick
var START_VALUE = 0; // initial value when it's the start date
var count = 0;

window.onload = function()
{
 var msInterval = INTERVAL * 1000;
 var now = new Date();
 count = parseInt((now - START_DATE)/msInterval,10) * INCREMENT + START_VALUE;
 document.getElementById('counter').innerHTML = count;
 setInterval("count += INCREMENT;document.getElementById('counter').innerHTML = count;", msInterval);
}

I would appreciate any help with this.

Thanks.

Palpatim
  • 9,074
  • 35
  • 43
gipson
  • 11
  • 1
  • Possible duplicate of [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – JJJ Oct 27 '15 at 22:30
  • Possible duplicate of [JavaScript math, round to two decimal places](http://stackoverflow.com/questions/15762768/javascript-math-round-to-two-decimal-places) – Palpatim Oct 27 '15 at 22:30

1 Answers1

1

You can just use toFixed(2) instead:

document.getElementById('counter').innerHTML = count.toFixed(2)
dave
  • 62,300
  • 5
  • 72
  • 93