im building a shopping cart for an application and im trying to get the total value of the sum between all the elements with the class ".totalPrice".
everything is working fine and the sum is being done correctly untill i try to sum values like 1.005.67 + 1.050.00, then the result is printed like this
this is my code:
function sum() {
var sum = 0;
$('.totalPrice').each(function () {
sum += parseFloat(this.value);
});
$("#total").text("Total: $" + sum.toFixed(2).replace(".",","));
}
<label>
<label> Value 1 </label>
<input type="text" class="totalPrice">
<br><br><br>
<label> Value 2 </label>
<input type="text" class="totalPrice">
<br><br><br>
<button onclick="sum()"> calculate </button>
<h1 id="total"> </h1>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
2
Answers
It’s because there are two decimal places within your inputs.
When you run
parseFloat("1.005.67")
, you get 1.005; and, from `parseFloat("1.050.00"), you get 1.05.Adding these numbers together, you get 2.055, which you’re then rounding to 2 decimal places, hence the result $2.05.
For the number to parse as you expect, the inputs must have only one decimal point.
Create an instance of
Intl.NumberFormat
and set it tocurrency
.Please, name variables appropriately. Do not have a variable and function with identical names. It is confusing for the reader.
Noe: If you set your
<input>
totype="number"
, you can set thestep
to account for 1/100ths and you can now grab the input value without parsing, withinput.valueAsNumber
.