计算数字有效位数的最快方法是什么?
我有以下功能,它可以工作,但由于字符串操作很慢.
/**
* 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
};
Run Code Online (Sandbox Code Playgroud)
有更快的方法吗?
更新:此处列出了测试正确运行的断言:
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);
Run Code Online (Sandbox Code Playgroud)
我自己的方法失败了digits(0),我通过?在第二个正则表达式中添加一个来修复它.
这是一种更加数学化的方式来做同样的操作(看起来明显更快)
JSPerf比较了这三种实现方式
n < +-(2^53)每个http://ecma262-5.com/ELS5_HTML.htm#Section_8.5 精确为整数
浮点数转换为字符串,然后强制转换为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
}
Run Code Online (Sandbox Code Playgroud)
小智 2
正则表达式略有改进
function digits (value) {
return value
.toExponential()
.replace(/^([0-9]+)\.?([0-9]+)?e[\+\-0-9]*$/g, "$1$2")
.length
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3142 次 |
| 最近记录: |