Performing Arithmetic on Currency Values in the form of Text using Javascript
I am using JQ开发者_C百科uery to get the contents of a div, which only contains a price in dollars and I would like to add $99 to it, but its text, so when I do the below it won't work.
$('#price_' + part[0]).text($('#price_' + part[0]).text() + 99);
//Changes the div contents to $10099 - if it the contents was $100 to start with
So the question is how can I add the numeric values?
Thanks all
Edit
Please note some numbers can contain a comma i.e. $1,200
Get numerical substring and cast it to a number:
$('#price_' + part[0]).text("$" + (+($('#price_' + part[0]).text()).substring(1) + 99));
Note the use of the unary +
operator to cast the string into a number, and the use of substring to get everything after the 1st ($) character in the string.
UPDATE
Since you mentioned the value can contain a comma, you'll be better off breaking this down a bit and performing a string replace:
var div = $('#price_' + part[0]); // get a ref to the div
// replace occurrences of `$` or `,`, cast to a number and add 99
var amount = +div.text().replace(/[$,]/g, '') + 99;
// set the new text to the div
div.text("$" + amount);
Something like this should work
var str = $(...).text();
var sum = parseInt(str.replace(/\D/g, ""));
$(...).text("$" + (sum + 99))
Use parseInt:
var price = $('#price_' + part[0]);
price.text(parseInt(price.text()) + 99);
You'll have to convert the text to int/float before doing the arithmatic
$('#price_' + part[0]).text( parseInt( $('#price_' + part[0]).text() ) + 99);
parseFloat in place of parseInt if you need/want.
精彩评论