如何格式化数字,例如
0.00012006 to 0.00012
0.00004494 to 0.0000449
0.000000022732 to 0.0000000227 without becoming a number like 2.3e-8
我想知道如何以快速/有效的方式更改这样的数字。
我想知道如何转换这些数字,但如果有人知道如何像那样格式化它,我也想知道。
像
这样使用yourNumber.toFixed(numberOfDigitsAfterDot)
:
function format(n) {
var _n = n;
// count the position of the first decimal
var count = 0;
do {
n = n * 10;
count++;
} while(n < 1);
return _n.toFixed(count + 2);
}
var num = 0.000000022732;
console.log(format(num));
您可以获取数字的位置并在上面添加 2 以toFixed
.
function three(v) {
var n = Math.floor(Math.log(v) / Math.LN10);
return v.toFixed(n < 2 ? 2 - n : 0);
}
var n = [0.00012006, 0.00004494, 0.000000022732, 0.100101, 0.1100001, 1.000001, 12000, 10, 1e10];
console.log(n.map(three));