Javascript:如何将数字舍入到 2 个非零小数
Javascript: how to round number to 2 non-zero decimals
没有 jQuery,我如何将浮点数舍入为 2 个非零小数(但仅在需要时 - 1.5 而不是 1.50)?
就像这样:
2.50000000004 -> 2.5
2.652 -> 2.65
2.655 -> 2.66
0.00000204 -> 0.000002
0.00000205 -> 0.0000021
我试过这段代码:
var r = n.toFixed(1-Math.floor(Math.log10(n)));
但n=0.00000205
隐含r=0.0000020
,这与上述条件冲突。
但是 n=0.0000020501
意味着 r=0.0000021
,这是可以的,所以错误只是 5 作为最后一个小数,应该四舍五入。
这应该可以满足您的要求:
function twoDecimals(n) {
var log10 = n ? Math.floor(Math.log10(n)) : 0,
div = log10 < 0 ? Math.pow(10, 1 - log10) : 100;
return Math.round(n * div) / div;
}
var test = [
2.50000000004,
2.652,
2.655,
0.00000204,
0.00000205,
0.00000605
];
test.forEach(function(n) {
console.log(n, '->', twoDecimals(n));
});
没有 jQuery,我如何将浮点数舍入为 2 个非零小数(但仅在需要时 - 1.5 而不是 1.50)?
就像这样:
2.50000000004 -> 2.5
2.652 -> 2.65
2.655 -> 2.66
0.00000204 -> 0.000002
0.00000205 -> 0.0000021
我试过这段代码:
var r = n.toFixed(1-Math.floor(Math.log10(n)));
但n=0.00000205
隐含r=0.0000020
,这与上述条件冲突。
但是 n=0.0000020501
意味着 r=0.0000021
,这是可以的,所以错误只是 5 作为最后一个小数,应该四舍五入。
这应该可以满足您的要求:
function twoDecimals(n) {
var log10 = n ? Math.floor(Math.log10(n)) : 0,
div = log10 < 0 ? Math.pow(10, 1 - log10) : 100;
return Math.round(n * div) / div;
}
var test = [
2.50000000004,
2.652,
2.655,
0.00000204,
0.00000205,
0.00000605
];
test.forEach(function(n) {
console.log(n, '->', twoDecimals(n));
});