简体   繁体   中英

How do i add a string dollar amount in javascript/jquery?

I have fields that have text like this

$4.00
$5.00
$55.90

and I want to add them in javascript to have a total of $64.90

I have this code

 var total= "";
 $("input:checkbox:not(.select_all):checked").closest("tr").each(function() {
    total += $(this).find(".amount").text().trim();
   });

My solution gives me this

 $4.00$5.00$55.90

Any idea what i am doing wrong

You're concatenating strings, you need to parse them as numbers first. You'll have to strip off the $ to do that. You also want to initialize total to 0 , not to an empty string:

var total = 0;
$("input:checkbox:not(.select_all):checked").closest("tr").each(function() {
    total += parseFloat($(this).find(".amount").text().trim().replace(/^$/, ''));
});

// If you want total to be a string containing the `$` just convert it back:
total = '$' + total;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM