[英]trim to 2 decimals
I have:我有:
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;"
Most numbers round ok to 2 decimal points which is what I need.大多数数字都可以精确到小数点后 2 位,这正是我所需要的。
However, with an example like但是,举个例子
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;"
Field 1 is returning 75.99000000000001
How can I trim to 75.99
consistently?字段 1 返回
75.99000000000001
如何始终修剪到75.99
?
var num = 5 / 6;
var display = num.toFixed(2)
num outputs: 0.8333333333333334
display outputs: "0.83"
How about this:这个怎么样:
parseFloat(document.getElementById('21.29').toFixed(2));
The toFixed method should take care of the rounding nicely for you. toFixed 方法应该为您很好地处理舍入。
Use the method toFixed(2)
to fix it at 2 decimal places:使用
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);
I had a similar issue - where I do not wanted to round the value but trim upto 2 decimals我有一个类似的问题 - 我不想四舍五入但修剪到小数点后两位
I got the perfect solution for by writing this function and using where ever needed to trim upto 2 decimals通过编写此 function 并在需要的地方使用最多 2 位小数,我得到了完美的解决方案
function upto2Decimal(num) {
if (num > 0)
return Math.floor(num * 100) / 100;
else
return Math.ceil(num * 100) / 100;
}
if you call如果你打电话
upto2Decimal(2.3699) or upto2Decimal(-2.3699)
// returns 2.36 or -2.36
check this solution using your JS console of the browser使用浏览器的 JS 控制台检查此解决方案
You can use:您可以使用:
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.