skip to Main Content

I have a price number that looks like this: $27,272.70000

I’m trying to make it look like this: $27,272.70

I’m stuck with trying different methods but here is what i’ve got so far:

jQuery(document).ready(function() {

   jQuery('.cart-table-wrapper #shopping-cart-table tbody > tr').each(function() {

   var the_sp_subtotal = jQuery(this).find('td.col-total.a-right span.price').text().replace("$", "");

   var new_sp_subtotal = parseFloat(the_sp_subtotal).toFixed(2); 
   console.log(new_sp_subtotal);

});

});

But the result that I get is: 27.00

Here is the fiddle – https://jsfiddle.net/zqe37xsk/1/

Can someone please help me, what I’m doing wrong?
Thank you

2

Answers


  1. parseFloat("27,272.70") returns 27 because the , in 27,272.70 is no longer part of a number.

    As an alternative approach you could replace the part behind the last thousands separator and call toFixed on that. Then you can just join everything back together.

    In your each function, use:

    const [dollar, ...separatedNumber] = jQuery(this).find('td.col-total.a-right span.price').text().split(/$|,/);
    
    separatedNumber[separatedNumber.length - 1] = Number(separatedNumber.slice(-1)).toFixed(2);
    
    console.log("$" + separatedNumber.join(","));
    
    Login or Signup to reply.
  2. To format a currency string properly you could use the toLocaleString function. For this to properly work you have to transform your string into a float.

    var price = '27,272.70000';
    price = parseFloat(price.replace(/[$,]/g, ""));
    
    console.log(price.toLocaleString('us-EN', {
      style: 'currency',
      currency: 'USD'
    }));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search