英文:
floating value not being shown up correctly
问题
I'm building a shopping cart for an application and I'm 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 until I try to sum values like 1,005.67 + 1,050.00; then the result is printed like this.
英文:
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:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function sum() {
var sum = 0;
$('.totalPrice').each(function () {
sum += parseFloat(this.value);
});
$("#total").text("Total: $" + sum.toFixed(2).replace(".",","));
}
<!-- language: lang-html -->
<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>
<!-- end snippet -->
答案1
得分: 1
因为您的输入中有两个小数点。
当您运行 parseFloat("1.005.67")
时,您得到的是 1.005;而从 parseFloat("1.050.00")
中,您得到的是 1.05。
将这些数字相加,您得到 2.055,然后将其四舍五入到两位小数点,因此结果是 2.05。
要使数字解析如您期望的那样,输入必须只有一个小数点。
英文:
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.
答案2
得分: 0
创建一个 Intl.NumberFormat
的实例,并将其设置为 currency
。
请适当命名变量。不要使用相同的变量名和函数名,这会让读者感到困惑。
**注意:**如果将 <input>
的 type
设置为 type="number"
,您可以设置 step
来考虑小数点后两位,并且现在可以使用 input.valueAsNumber
来获取输入值,而无需解析。
const currencyFormatter = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
const calculateSumAndDisplay = () => {
const sum = [...document.querySelectorAll('.totalPrice')]
.reduce((total, input) => total + input.valueAsNumber, 0);
document.querySelector('#total')
.textContent = `Total: ${currencyFormatter.format(sum)}`;
}
<label>Value 1</label>
<input type="number" class="totalPrice" step="0.01" />
<br>
<label>Value 2</label>
<input type="number" class="totalPrice" step="0.01" />
<br>
<button type="button" onclick="calculateSumAndDisplay()">Calculate</button>
<h1 id="total"></h1>
英文:
Create an instance of Intl.NumberFormat
and set it to currency
.
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>
to type="number"
, you can set the step
to account for 1/100ths and you can now grab the input value without parsing, with input.valueAsNumber
.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const currencyFormatter = new Intl.NumberFormat('en-US',
{ style: 'currency', currency: 'USD' });
const calculateSumAndDisplay = () => {
const sum = [...document.querySelectorAll('.totalPrice')]
.reduce((total, input) => total + input.valueAsNumber, 0);
document.querySelector('#total')
.textContent = `Total: ${currencyFormatter.format(sum)}`;
}
<!-- language: lang-html -->
<label>Value 1</label>
<input type="number" class="totalPrice" step="0.01" />
<br>
<label>Value 2</label>
<input type="number" class="totalPrice" step="0.01" />
<br>
<button type="button" onclick="calculateSumAndDisplay()">Calculate</button>
<h1 id="total"></h1>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论