Search code examples
javascriptcounterparseint

Restrict JS Counter to Two Number Decimals


I have a JS counter which is working perfectly, but I want to restrict it to two numbers after the decimal point. Right now it can go as high as 9. Any ideas for solutions which won't mess up the rest of the code?

Here's a JSFiddle with my code, also listed below: https://jsfiddle.net/nd252525/26pvd7g3/3/

var INTERVAL_FIRST = 1;
var INCREMENT_FIRST = 0.86;
var START_VALUE_FIRST = 12574343;
var COUNT_FIRST = 0;

window.onload = function () {
  var msInterval2 = INTERVAL_FIRST * 1000;
  var NOW_FIRST = new Date();
  COUNT_FIRST =
    parseInt((NOW_FIRST - START_DATE) / msInterval2) * INCREMENT_FIRST +
    START_VALUE_FIRST;
  document.getElementById("first-ticker").innerHTML = addCommas(COUNT_FIRST);
  setInterval(
    "COUNT_FIRST += INCREMENT_FIRST; document.getElementById('first-ticker').innerHTML = addCommas(COUNT_FIRST);",
    msInterval2
  );
};

function addCommas(nStr) {
  nStr += "";
  x = nStr.split(".");
  x1 = x[0];
  x2 = x.length > 1 ? "." + x[1] : "";
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, "$1" + "," + "$2");
  }
  return x1 + x2;
}

Any help is greatly appreciated, thanks :)


Solution

  • You can apply the .toFixed(2) method to your COUNT_FIRST variable to restrict it to 2 digits after the decimal point.

    Your code will look like this:

    window.onload = function () {
      var msInterval2 = INTERVAL_FIRST * 1000;
      var NOW_FIRST = new Date();
      COUNT_FIRST =
        parseInt((NOW_FIRST - START_DATE) / msInterval2) * INCREMENT_FIRST +
        START_VALUE_FIRST;
      
      // Add one here
      document.getElementById("first-ticker").innerHTML = addCommas(COUNT_FIRST.toFixed(2));
    
      // And one more here
      setInterval(
        "COUNT_FIRST += INCREMENT_FIRST; document.getElementById('first-ticker').innerHTML = addCommas(COUNT_FIRST.toFixed(2));",
        msInterval2
      );
    };
    

    The code was tested with your provided JSFiddle.