Jus*_*siR 33 javascript math floating-point
我想要的是与Number.prototype.toPrecision()几乎相反,这意味着当我有数字时,它有多少小数?例如
(12.3456).getDecimals() // 4
Run Code Online (Sandbox Code Playgroud)
Mou*_*ner 44
对于任何想知道如何更快地做到这一点(没有转换为字符串)的人,这是一个解决方案:
function precision(a) {
var e = 1;
while (Math.round(a * e) / e !== a) e *= 10;
return Math.log(e) / Math.LN10;
}
Run Code Online (Sandbox Code Playgroud)
编辑:涵盖边缘案例的更完整的解决方案:
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;
}
Run Code Online (Sandbox Code Playgroud)
Man*_*ish 26
一种可能的解决方案(取决于应用程序):
var precision = (12.3456 + "").split(".")[1].length;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32125 次 |
| 最近记录: |