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:
- prod 1: 200
- prod 2: 200
- prod 3: 500
- total: 900
But when the numbers are greater then "1,000", the comma is the problem. I get a wrong answer.
ex:
- prod 1: 200
- prod 2: 1,200
- prod 3: 300
- 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>
question from:
https://stackoverflow.com/questions/65919287/sum-numbers-with-javascript-doesnt-work-properly-intl-numberformat 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…