Javascript can';t使用jQuery添加两个十进制数
我尝试添加两个十进制值,但返回的和是纯整数。怎么了?我找不到它。欢迎任何帮助Javascript can';t使用jQuery添加两个十进制数,javascript,jquery,decimal,Javascript,Jquery,Decimal,我尝试添加两个十进制值,但返回的和是纯整数。怎么了?我找不到它。欢迎任何帮助 jQuery(".delivery-method #ship_select").change(function(){ var cost = jQuery(this).val(); jQuery("#delivery_cost").val(cost); //returns 20.00 var tot = parseInt(cost) + parseInt(total); //total retu
jQuery(".delivery-method #ship_select").change(function(){
var cost = jQuery(this).val();
jQuery("#delivery_cost").val(cost); //returns 20.00
var tot = parseInt(cost) + parseInt(total); //total returns 71.96
});
对于代码,我只得到91
而不是91.96
使用parseFloat()
而不是parseInt()
jQuery(".delivery-method #ship_select").change(function(){
var cost = jQuery(this).val();
jQuery("#delivery_cost").val(cost); //returns 20.00
var tot = parseFloat(cost) + parseFloat(total); //total returns 71.96
});
使用parseFloat代替parseInt并检查。整数算术四舍五入。使用
parseFloat
代替。使用parseFloat()
代替parseInt()
但是,由于您希望严格限制小数点后两位
function roundNumber(num, dec) {
var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
return result;
}
var tot = roundNumber((cost+total), 2);
您必须使用
parseFloat
而不是parseInt
var tot = parseFloat(cost) + parseFloat(total);
jQuery(".delivery-method #ship_select").change(function(){
var cost = jQuery(this).val();
jQuery("#delivery_cost").val(cost); //returns 20.00
var tot = parseFloat(cost) + parseFloat(total); //total returns 71.96
});
检查演示:parseInt()终止逗号值