假设我的值为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.815.7815.77815.7784514000如何显示15.77?
3 回答
四季花海
TA贡献1811条经验 获得超5个赞
将数字转换为字符串,将数字匹配到小数点第二位:
function calc(theform) {
var num = theform.original.value, rounded = theform.rounded
var with2Decimals = num.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]
rounded.value = with2Decimals
}
<form onsubmit="return calc(this)">
Original number: <input name="original" type="text" onkeyup="calc(form)" onchange="calc(form)" />
<br />"Rounded" number: <input name="rounded" type="text" placeholder="readonly" readonly>
</form>
toFixed
toString
蝴蝶不菲
TA贡献1810条经验 获得超4个赞
新答案,总是准确的
function toFixed(num, fixed) { var re = new RegExp('^-?\\d+(?:\.\\d{0,' + (fixed || -1) + '})?'); return num.toString().match(re)[0];}
num.toPrecision
, bigDecimal.js
旧的答案,并不总是准确的。
function toFixed(num, fixed) { fixed = fixed || 0; fixed = Math.pow(10, fixed); return Math.floor(num * fixed) / fixed;}
添加回答
举报
0/150
提交
取消