nev*_*ing 4 javascript string-formatting number-formatting
我想将数字(以字符串形式给出)截断为固定的小数位数.数字可以是负数(带减号),正数(无符号).我更喜欢正确地对数字进行舍入并保持尾随零.我想要相同的小数位数,无论整数是多长.数字将作为字符串存储回来.
例如:
140.234234234 -> 140.234
1.123123 -> 1.123
-12.789789 -> -12.790
Run Code Online (Sandbox Code Playgroud)
首先将它们解析为浮点数,然后格式化为toFixed:
var nums = [
"140.234234234", // -> 140.234
"1.123123", // -> 1.123
"-12.789789" // -> -12.790
];
nums.forEach(function(n) {
console.log(parseFloat(n).toFixed(3));
});
Run Code Online (Sandbox Code Playgroud)
http://codepen.io/anon/pen/IvxmA
| 归档时间: |
|
| 查看次数: |
5530 次 |
| 最近记录: |