Search code examples
javascriptmathfloating-point

How do I get the decimal places of a floating point number in Javascript?


What I would like to have is the almost opposite of Number.prototype.toPrecision(), meaning that when i have number, how many decimals does it have? E.g.

(12.3456).getDecimals() // 4

Solution

  • For anyone wondering how to do this faster (without converting to string), here's a solution:

    function precision(a) {
      var e = 1;
      while (Math.round(a * e) / e !== a) e *= 10;
      return Math.log(e) / Math.LN10;
    }
    

    Edit: a more complete solution with edge cases covered:

    function precision(a) {
      if (!isFinite(a)) return 0;
      var e = 1, p = 0;
      while (Math.round(a * e) / e !== a) { e *= 10; p++; }
      return p;
    }