在jQuery中将值转换为2个小数位 [英] Converting a value to 2 decimal places within jQuery
问题描述
可能重复:
JavaScript:格式化数字正好两位小数
<现在我已经有一些脚本将值添加到div中,其中包含一个总数,然后我尝试将值除以100以得到一个十进制数(使其看起来像货币)。
Now that I have got a bit of script to add values in to a div with a total in it, I then try to divide the values by 100 to give me a decimal number (to make it look like currency).
在此之后脚本工作并给我一个很好的十进制浮点数,有时虽然后来有一个大的重复数字,但是我想用脚本将其限制为两位小数我已经有人想知道是否有人可以在我当前的脚本中实现某些内容。
After this the script works and gives me a nice decimal float, sometimes though a large recurring number comes after, I want to limit this to two decimals using the script i already have so was wondering if someone could implement something into my current script.
$(document).ready(function() {
$('.add').click(function() {
$('#total').text(parseFloat($('#total').text()) + parseFloat($(this).data('amount'))/100);
});
})
推荐答案
您需要使用 .toFixed()
方法
You need to use the .toFixed()
method
以小数点后显示的位数作为参数点。
It takes as a parameter the number of digits to show after the decimal point.
$(document).ready(function() {
$('.add').click(function() {
var value = parseFloat($('#total').text()) + parseFloat($(this).data('amount'))/100
$('#total').text( value.toFixed(2) );
});
})
这篇关于在jQuery中将值转换为2个小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!