Javascript 修剪为 2 位小数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6525335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
trim to 2 decimals
提问by user821522
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
始终保持一致?
回答by Bobby Borszich
var num = 5 / 6;
var display = num.toFixed(2)
num outputs: 0.8333333333333334
display outputs: "0.83"
回答by Michael Berkowski
Use the method toFixed(2)
to fix it at 2 decimal places:
使用方法toFixed(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);
回答by Sean McMains
How about this:
这个怎么样:
parseFloat(document.getElementById('21.29').toFixed(2));
The toFixed method should take care of the rounding nicely for you.
toFixed 方法应该很好地为您处理舍入。
回答by Abdeali Chandanwala
I had a similar issue - where I do not wanted to round the value but trim upto 2 decimals
我有一个类似的问题 - 我不想四舍五入该值但修剪到 2 位小数
I got the perfect solution for by writing this function and using where ever needed to trim upto 2 decimals
通过编写此函数并使用需要修剪至 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 控制台检查此解决方案