Thousands separator in jQuery is causing parseFloat to misinterpret numbers

1.7k views Asked by At

I am using a . as a thousands separator. So the string 128.814 should be read as "one hundred and twenty eight thousand, eight hundred and fourteen".

When I add this to the number 900, I want the answer to be 129714 (displayed as 129.714). However, because javascript takes the thousands separator as a decimal point, it's giving me an undesirable result.

function addTotalPrice(item){
    var priceItem = parseFloat( $(item).find('.price').text() );
    var priceTotal = parseFloat( $('.label-price span').text() );

    var result = (priceTotal + priceItem);
    $('.label-price span').text( result.toFixed(3) );
}

How can I tell jQuery/Javascript to interpret the . in 128.814 as a thousands separator and not a decimal point?

1

There are 1 answers

1
AmmarCSE On BEST ANSWER

How can I tell jQuery/Javascript to interpret the . in 128.814 as a thousands separator and not a decimal point?

Simplest way would be to remove it.

When you remove it, it will automatically be interpreted as a thousands value, even without the comma there. Then, manually format the number like in How to print a number with commas as thousands separators in JavaScript

function addTotalPrice(item){
    var priceItem = parseFloat( $(item).find('.price').text().replace('.','') );
    var priceTotal = parseFloat( $('.label-price span').text().replace('.','') );

    var result = (priceTotal + priceItem);
    $('.label-price span').text( result.toString().replace(/\B(?=(\d{3})+(?!\d))/g, "."); );
}

var priceItem = parseFloat('900'.replace('.', ''));
var priceTotal = parseFloat('128.814'.replace('.', ''));

var result = (priceTotal + priceItem);
var fixedResult = result.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
document.write(fixedResult);