Saar Asor
Saar Asor

Reputation: 29

Sum numbers with JavaScript doesn't work properly "Intl.NumberFormat"

I have page with table of products and for each product there is a price. When I change the qty it gets the total price...

But I have this problem: When the numbers are lower then "1,000", the sum is ok.

ex:

  1. prod 1: 200
  2. prod 2: 200
  3. prod 3: 500
  4. total: 900

But when the numbers are greater then "1,000", the comma is the problem. I get a wrong answer.

ex:

  1. prod 1: 200
  2. prod 2: 1,200
  3. prod 3: 300
  4. total: 501

When I remove the "Intl.NumberFormat" from the total of each product, I get the right answer, but for some cases I get numbers like this: "1.000031545", which I don't need. I only need the first 2 digit after the dot.

CODE: (simplefied)

<table>
    <tr>
       <td style="text-align: center;">
           <label for="prod[<?php echo $prodid; ?>]"><input class='qty' style="font-size: 12px;" type="text" name="qty_<?php echo $prodid; ?>" placeholder="qty" minlength="1" maxlength="3" size="2"></label>
       </td>
       <td class='price'>
           <?php echo $prodprice; ?>
       </td>
       <td width="40" class="sum">0</td>
    </tr>
    <tr>
       <td colspan="3">
           <span class="output"></span>
       </td>
</table>

<script type="text/javascript">

function getTotal(){
    var total = 0;
    $('.sum').each(function(){
        total += parseFloat(this.innerHTML);
    });

    $('#total').text(total);

            givenNumber = total; 
            nfObject = new Intl.NumberFormat('en-US'); 
            output = nfObject.format(givenNumber); 
            document.querySelector('.output').textContent = total; 
}

getTotal();

$('.qty').keyup(function(){
    var parent = $(this).parents('tr');
    var price = $('.price', parent);
    var sum = $('.sum', parent);
    var value = parseInt(this.value) * parseFloat(price.get(0).innerHTML||0);
            givenNum1 = value; 
            nfObj = new Intl.NumberFormat('en-US'); 
            outpu = nfObj.format(givenNum1); 
    sum.text(outpu);
    getTotal();
})

</script>

Upvotes: 0

Views: 707

Answers (2)

Aalexander
Aalexander

Reputation: 5004

Referencing the MDN Web Docs

If parseFloat encounters a character other than a plus sign (+), minus sign (- U+002D HYPHEN-MINUS), numeral (0–9), decimal point (.), or exponent (e or E), it returns the value up to that character, ignoring the invalid character and characters following it.

You can remove the comma by using replace() and then parse it afterwards to get the right value.

let str = "1,200"
let newStr = str.replace(/,/g,"");


console.log(`Without replace ${parseFloat(str)}`);
console.log(`With replace ${newStr}`);

Upvotes: 3

T.J. Crowder
T.J. Crowder

Reputation: 1074919

parseFloat stops parsing at the first invalid character. , is not a valid character to parseFloat.

You can remove the ,:

total += parseFloat(this.textContent.replace(/,/g, ""));

Note that I also switched from innerHTML to textContent.

Also note that I used a regular expression with the g ("global") flag, since .replace(",", "") would only replace the first comma (so 1,200,300 would fail). Or in modern environments you can use replaceAll but it's relatively new (though easily polyfilled):

total += parseFloat(this.textContent.replaceAll(",", ""));

For this I'd just use the regular expression.

Upvotes: 1

Related Questions