Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Number of Decimal Places with Javascript

Tags:

javascript

How would I calculate the number of decimal places (not digits) of a real number with Javascript?

function countDecimals(number) {

}

For example, given 245.395, it should return 3.

like image 319
Octocat Avatar asked Nov 22 '14 20:11

Octocat


4 Answers

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);
like image 61
Alex Filatov Avatar answered Nov 13 '22 09:11

Alex Filatov


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);
like image 38
Gosha_Fighten Avatar answered Nov 13 '22 09:11

Gosha_Fighten


Here is a method that does not rely on converting anything to string:

function getDecimalPlaces(x,watchdog)
{
    x = Math.abs(x);
    watchdog = watchdog || 20;
    var i = 0;
    while (x % 1 > 0 && i < watchdog)
    {
        i++;
        x = x*10;
    }
    return i;
}

Note that the count will not go beyond watchdog value (defaults to 20).

like image 1
jahu Avatar answered Nov 13 '22 10:11

jahu


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
      }
    }
like image 1
David Wyness Avatar answered Nov 13 '22 10:11

David Wyness