javascript – 计算数字有效位数的最快方法是什么?

计算数字有效位数的最快方法是什么?

我有以下功能,它可以工作,但由于字符串操作很慢.

/**
 * Count the number of significant digits of a number.
 *
 * For example:
 *   2.34 returns 3
 *   0.0034 returns 2
 *   120.5e+3 returns 4
 *
 * @param {Number} value
 * @return {Number} The number of significant digits
 */
function digits (value) {
  return value
      .toExponential()
      .replace(/e[\+\-0-9]*$/,'')  // remove exponential notation
      .replace( /^0\.?0*|\./,'')    // remove decimal point and leading zeros
      .length
};

有更快的方法吗?

更新:此处列出了测试正确运行的断言:

assert.equal(digits(0),0);
assert.equal(digits(2),1);
assert.equal(digits(1234),4);
assert.equal(digits(2.34),3);
assert.equal(digits(3000),1);
assert.equal(digits(0.0034),2);
assert.equal(digits(120.5e50),4);
assert.equal(digits(1120.5e+50),5);
assert.equal(digits(120.52e-50),5);
assert.equal(digits(Math.PI),16);

我自己的方法对于数字(0)失败,我通过添加一个?到第二个正则表达式.

解决方法

这是一种更加数学化的方式来做同样的操作(看起来明显更快)

JSPerf比较了三种实现方式

准确的整数n< - 每个http://ecma262-5.com/ELS5_HTML.htm#Section_8.5(2 ^ 53)
将浮点数转换为字符串,然后强制转换为int(通过删除小数,因此应用类似的规则)

var log10 = Math.log(10);
function getSignificantDigitCount(n) {
    n = Math.abs(String(n).replace(".","")); //remove decimal and make positive
    if (n == 0) return 0;
    while (n != 0 && n % 10 == 0) n /= 10; //kill the 0s at the end of n

    return Math.floor(Math.log(n) / log10) + 1; //get number of digits
}

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...