Is there a reliable way in JavaScript to obtain the number of decimal places of an arbitrary number?

前端 未结 7 1341
一整个雨季
一整个雨季 2020-12-01 10:15

It\'s important to note that I\'m not looking for a rounding function. I am looking for a function that returns the number of decimal places in an arbitrary number\'s simpli

相关标签:
7条回答
  • 2020-12-01 11:19

    Well, I use a solution based on the fact that if you multiply a floating-point number by the right power of 10, you get an integer.

    For instance, if you multiply 3.14 * 10 ^ 2, you get 314 (an integer). The exponent represents then the number of decimals the floating-point number has.

    So, I thought that if I gradually multiply a floating-point by increasing powers of 10, you eventually arrive to the solution.

    let decimalPlaces = function () {
       function isInt(n) {
          return typeof n === 'number' && 
                 parseFloat(n) == parseInt(n, 10) && !isNaN(n);
       }
       return function (n) {
          const a = Math.abs(n);
          let c = a, count = 1;
          while (!isInt(c) && isFinite(c)) {
             c = a * Math.pow(10, count++);
          }
          return count - 1;
       };
    }();
    
    for (const x of [
      0.0028, 0.0029, 0.0408,
      0, 1.0, 1.00, 0.123, 1e-3,
      3.14, 2.e-3, 2.e-14, -3.14e-21,
      5555.0, 5555, 555.5, 555.50, 0.0000005, 5e-7, 0.00000055, 5e-8,
      0.000006, 0.0000007,
      0.123, 0.121, 0.1215
    ]) console.log(x, '->', decimalPlaces(x));

    0 讨论(0)
提交回复
热议问题