Get Number of Decimal Places with Javascript

Like this:

var val = 37.435345;
var countDecimals = function(value) {
  let text = value.toString()
  // verify if number 0.000005 is represented as "5e-6"
  if (text.indexOf('e-') > -1) {
    let [base, trail] = text.split('e-');
    let deg = parseInt(trail, 10);
    return deg;
  }
  // count decimals for number in representation like "0.123456"
  if (Math.floor(value) !== value) {
    return value.toString().split(".")[1].length || 0;
  }
  return 0;
}
countDecimals(val);

The main idea is to convert a number to string and get the index of "."

var x = 13.251256;
var text = x.toString();
var index = text.indexOf(".");
alert(text.length - index - 1);

I tried some of the solutions in this thread but I have decided to build on them as I encountered some limitations. The version below can handle: string, double and whole integer input, it also ignores any insignificant zeros as was required for my application. Therefore 0.010000 would be counted as 2 decimal places. This is limited to 15 decimal places.

  function countDecimals(decimal)
    {
    var num = parseFloat(decimal); // First convert to number to check if whole

    if(Number.isInteger(num) === true)
      {
      return 0;
      }

    var text = num.toString(); // Convert back to string and check for "1e-8" numbers
    
    if(text.indexOf('e-') > -1)
      {
      var [base, trail] = text.split('e-');
      var deg = parseInt(trail, 10);
      return deg;
      }
    else
      {
      var index = text.indexOf(".");
      return text.length - index - 1; // Otherwise use simple string function to count
      }
    }

Tags:

Javascript