jQuery 将值四舍五入到 2 位小数 javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14666752/
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
round value to 2 decimals javascript
提问by Dario
I have a small issue with the final value, i need to round to 2 decimals.
我对最终值有一个小问题,我需要四舍五入到小数点后两位。
var pri='#price'+$(this).attr('id').substr(len-2);
$.get("sale/price?output=json", { code: v },
function(data){
$(pri).val(Math.round((data / 1.19),2));
});
});
Any help is appreciated.
任何帮助表示赞赏。
Solution: $(pri).val(Math.round((data / 1.19 * 100 )) / 100);
解决方案: $(pri).val(Math.round((data / 1.19 * 100 )) / 100);
采纳答案by David
Just multiply the number by 100, round, and divide the resulting number by 100.
只需将数字乘以 100,四舍五入,然后将所得数字除以 100。
回答by Phrogz
If you want it visually formatted to two decimals as a string (for output) use toFixed()
:
如果您希望将其直观地格式化为两位小数作为字符串(用于输出),请使用toFixed()
:
var priceString = someValue.toFixed(2);
The answer by @David has two problems:
@David 的回答有两个问题:
It leaves the result as a floating point number, and consequently holds the possibility of displaying a particular result with many decimal places, e.g.
134.1999999999
instead of"134.20"
.If your value is an integer or rounds to one tenth, you will not see the additional decimal value:
var n = 1.099; (Math.round( n * 100 )/100 ).toString() //-> "1.1" n.toFixed(2) //-> "1.10" var n = 3; (Math.round( n * 100 )/100 ).toString() //-> "3" n.toFixed(2) //-> "3.00"
它将结果保留为浮点数,因此可以显示具有许多小数位的特定结果,例如
134.1999999999
代替"134.20"
。如果您的值是整数或四舍五入到十分之一,您将不会看到额外的十进制值:
var n = 1.099; (Math.round( n * 100 )/100 ).toString() //-> "1.1" n.toFixed(2) //-> "1.10" var n = 3; (Math.round( n * 100 )/100 ).toString() //-> "3" n.toFixed(2) //-> "3.00"
And, as you can see above, using toFixed()
is also far easier to type. ;)
而且,正如您在上面看到的,使用toFixed()
也更容易打字。;)