假设我的值为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?
将数字转换为字符串,将数字匹配到小数点后第二位:
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,因此请务必小心。
toFixed
toString