[英]trim to 2 decimals
我有:
onclick="document.getElementById('field1').value =
Math.round((parseFloat(document.getElementById('field2').value,2)*100))/100 +
Math.round((parseFloat(document.getElementById('field3').value,2)*100))/100;"
大多数数字都可以精确到小数点后 2 位,这正是我所需要的。
但是,举个例子
onclick="document.getElementById('field1').value =
Math.round((parseFloat(document.getElementById('21.29').value,2)*100))/100 +
Math.round((parseFloat(document.getElementById('54.70').value,2)*100))/100;"
字段 1 返回75.99000000000001
如何始终修剪到75.99
?
var num = 5 / 6;
var display = num.toFixed(2)
num outputs: 0.8333333333333334
display outputs: "0.83"
这个怎么样:
parseFloat(document.getElementById('21.29').toFixed(2));
toFixed 方法应该为您很好地处理舍入。
使用toFixed(2)
方法将其固定在小数点后 2 位:
(Math.round((parseFloat(document.getElementById('21.29').value,2)*100))/100 +
Math.round((parseFloat(document.getElementById('54.70').value,2)*100))/100).toFixed(2);
我有一个类似的问题 - 我不想四舍五入但修剪到小数点后两位
通过编写此 function 并在需要的地方使用最多 2 位小数,我得到了完美的解决方案
function upto2Decimal(num) {
if (num > 0)
return Math.floor(num * 100) / 100;
else
return Math.ceil(num * 100) / 100;
}
如果你打电话
upto2Decimal(2.3699) or upto2Decimal(-2.3699)
// returns 2.36 or -2.36
使用浏览器的 JS 控制台检查此解决方案
您可以使用:
function myFunction() { var num = "-54.987656"; var roundedValue = roundMethod(num,5); document.getElementById("demo").innerHTML = roundedValue; } function roundMethod(numberVal, roundLimit) // This method will not add any additional 0, if decimal places are less than the round limit { var isDecimal = numberVal.indexOf(".");= -1. if(isDecimal) { if(numberVal.split(".")[1].length > roundLimit) { return parseFloat(numberVal).toFixed(roundLimit);toString(); }else { return numberVal; } }else { return numberVal; } }
<html> <body> <p>Click the button to display the fixed number.</p> <button onclick="myFunction()">Try it</button> <p id="demo"></p> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.