在jQuery中将值转换为2个小数位[重复]

时间:2021-03-25 16:35:39

Possible Duplicate:
JavaScript: formatting number with exactly two decimals

可能重复:JavaScript:格式化数字,正好是两位小数

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).

现在我已经有了一些脚本来将值添加到div中的div中,然后我尝试将值除以100以给出一个十进制数(使其看起来像货币)。

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);
  });
})

3 个解决方案

#1


55  

You need to use the .toFixed() method

您需要使用.toFixed()方法

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) );
  });
})

#2


12  

Try to use this

试着用这个

parseFloat().toFixed(2)

#3


4  

you can use just javascript for it

你可以只使用javascript

var total =10.8
(total).toFixed(2); 10.80


alert(total.toFixed(2))); 

#1


55  

You need to use the .toFixed() method

您需要使用.toFixed()方法

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) );
  });
})

#2


12  

Try to use this

试着用这个

parseFloat().toFixed(2)

#3


4  

you can use just javascript for it

你可以只使用javascript

var total =10.8
(total).toFixed(2); 10.80


alert(total.toFixed(2)));