将数字转换为字符串,将数字匹配到小数点后第二位:
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,因此请务必小心。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)