假设我有一个值15.7784514,我想把它显示为15.77,没有舍入。
var num = parseFloat(15.7784514);
document.write(num.toFixed(1)+"<br />");
document.write(num.toFixed(2)+"<br />");
document.write(num.toFixed(3)+"<br />");
document.write(num.toFixed(10));
结果:
15.8
15.78
15.778
15.7784514000
如何显示15.77?
2016年11月5日更新
新的答案,总是准确的
function toFixed(num, fixed) {
var re = new RegExp('^-?\\d+(?:\.\\d{0,' + (fixed || -1) + '})?');
return num.toString().match(re)[0];
}
由于javascript中的浮点数学总是有边缘情况,所以之前的解决方案在大多数情况下都是准确的,这是不够的。
有一些解决方案,如num.toPrecision, BigDecimal.js和accounting.js。
然而,我相信仅仅解析字符串是最简单的,而且总是准确的。
基于@Gumbo接受的答案的良好编写的正则表达式的更新,这个新的toFixed函数将始终按预期工作。
老答案,并不总是准确的。
固定功能:
function toFixed(num, fixed) {
fixed = fixed || 0;
fixed = Math.pow(10, fixed);
return Math.floor(num * fixed) / fixed;
}
截断不带零
function toTrunc(value,n){
return Math.floor(value*Math.pow(10,n))/(Math.pow(10,n));
}
or
function toTrunc(value,n){
x=(value.toString()+".0").split(".");
return parseFloat(x[0]+"."+x[1].substr(0,n));
}
测试:
toTrunc(17.4532,2) //17.45
toTrunc(177.4532,1) //177.4
toTrunc(1.4532,1) //1.4
toTrunc(.4,2) //0.4
用零截断
function toTruncFixed(value,n){
return toTrunc(value,n).toFixed(n);
}
测试:
toTrunc(17.4532,2) //17.45
toTrunc(177.4532,1) //177.4
toTrunc(1.4532,1) //1.4
toTrunc(.4,2) //0.40