[英]Decimals in javascript
如何在javascript中转换此输出:
a = 1.0000006
b = 0.00005
c = 2.54695621e-7
到此输出:
a = 1
b = 5e-5
c = 2.547e-7
尝试以下代码:
var a = 1.0000006; var b = 0.00005; var c = 2.54695621e-7; var a_Result = Math.round(a); var b_Result = b.toExponential(); var c_Result = c.toExponential(3); console.log(a_Result ); console.log(b_Result); console.log(c_Result);
使用此输入:
var nums = [1.0000006, 0.00005, 2.54695621e-7];
您可以使用Number#toExponential
获取具有一定精度的指数表示法:
function formatNumber(n) {
return n.toExponential(3);
}
nums.map(formatNumber)
// ["1.000e+0", "5.000e-5", "2.547e-7"]
分成有用的部分:
function formatNumber(n) {
return n
.toExponential(3)
.split(/[.e]/);
}
nums.map(formatNumber)
// [["1", "000", "+0"], ["5", "000", "-5"], ["2", "547", "-7"]]
并删除不必要的内容:
function formatNumber(n) {
var parts = n
.toExponential(3)
.split(/[.e]/);
var integral = parts[0];
var fractional = '.' + parts[1];
var exponent = 'e' + parts[2];
fractional = fractional.replace(/\.?0+$/, '');
exponent = exponent === 'e+0' ? '' : exponent;
return integral + fractional + exponent;
}
nums.map(formatNumber)
// ["1", "5e-5", "2.547e-7"]
ES6:
const formatNumber = n => {
const [, integral, fractional, exponent] =
/(\d+)(\.\d+)(e.\d+)/.exec(n.toExponential(3));
return integral +
fractional.replace(/\.?0+$/, '') +
(exponent === 'e+0' ? '' : exponent);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.