0

i have problem calculate 2 numbers has comma in jquery or javascript

i take the first and second number from div "attr"

this is my example code

var firstnumber = $('.first_price').attr('price'); //its 5,000
var secondnumber = $('.second_price').attr('price'); //its 6,000

$('#total').html( Math.floor(firstnumber+secondnumber) );

//also tried
$('#total').html( Number(firstnumber+secondnumber) );

its return 0 , but when i remove the comma from the price its retruen 11000 how to make it return 11,000 i mean i need it to calculate the two numbers if they has comma any help ?

4

5 回答 5

1

这是答案:

var firstnumber = $('.first_price').data('price').replace( /[\$,]/g, '' ) ; 
var secondnumber = $('.second_price').data('price').replace( /[\$,]/g, '' ) ;
var total = Math.floor(firstnumber+secondnumber)
$('#total').html( formatCurrency(total)  );


function formatCurrency( amount ) {
amount = ('' + amount).replace( /[$,]/g, '' );
if( isNaN( amount ))
    amount = '0';

var cents = Math.round( amount * 100 ); // Total number of cents
amount = Math.abs( amount > 0 ? Math.floor(amount) : Math.ceil(amount) ) + ''; // Number of complete dollars

for( var i = 0; i < Math.floor( (amount.length - ( 1 + i )) / 3 ); i++ )
    amount = [amount.substring( 0, amount.length - ( 4 * i + 3 ) ), amount.substring( amount.length - ( 4 * i + 3 ))].join(',');

return (cents >= 0 ? '' : '-') + amount + '.' + (Math.abs(cents) % 100).zeroFill(2);

}

于 2012-09-12T19:56:23.077 回答
1

您必须删除逗号,然后重新应用逗号

var firstnumber = $('.first_price').data('price');
var secondnumber = $('.second_price').data('price');
firstnumber  = firstnumber.replace(/,/g , '');
secondnumber = secondnumber.replace(/,/g , '');
var result = addCommas(firstnumber+secondnumber);

添加逗号的功能

function addCommas(nStr){
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
于 2012-09-12T19:50:28.847 回答
0

您需要将字符串转换为数字:

var firstnumber = +$('.first_price').attr('price');
var secondnumber = +$('.second_price').attr('price');

但是,与其使用纯字符串的无效属性,不如考虑data-price="5000"在您的 HTML 中使用;那么以下代码将正常工作:

var firstnumber = $('.first_price').data('price');
var secondnumber = $('.second_price').data('price');

哦,不要把那几千个分隔符放在你的价格里。它们根本不属于数据;那是一个显示的东西。如果您无法摆脱它们,您需要在这两种情况下都转换为 int 但首先将它们删除 ( .replace(/,/g, ''))

于 2012-09-12T19:48:28.687 回答
0

因为还不是数字,是字符串,去掉逗号

var firstnumber = $('.first_price').attr('price').replace(/[^\d.]/g,''); //its 5,000
var secondnumber = $('.second_price').attr('price').replace(/[^\d.]/g,''); //its 6,000

$('#total').html( Math.floor(firstnumber+secondnumber) );

我将正则表达式更改为仅保留有效的数值(数字和小数位)并删除其余部分。由于这些是价格,负数应该是一个问题。

于 2012-09-12T19:50:37.933 回答
0

尝试:

$('#total').html(  Math.floor(parseInt(firstnumber.replace(',',''),10)+parseInt(secondnumber.replace(',',''),10)) ));

jsFiddle 示例

在将字符串解析为整数之前,您需要去掉逗号。

于 2012-09-12T19:52:40.563 回答