浮点值未正确显示

huangapple go评论62阅读模式
英文:

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;
  $(&#39;.totalPrice&#39;).each(function () {
    sum += parseFloat(this.value);
  });
  $(&quot;#total&quot;).text(&quot;Total: $&quot; + sum.toFixed(2).replace(&quot;.&quot;,&quot;,&quot;));        
}

<!-- language: lang-html -->

&lt;label&gt;
&lt;label&gt; Value 1 &lt;/label&gt;
&lt;input type=&quot;text&quot; class=&quot;totalPrice&quot;&gt;
&lt;br&gt;&lt;br&gt;&lt;br&gt;
&lt;label&gt; Value 2 &lt;/label&gt;
&lt;input type=&quot;text&quot; class=&quot;totalPrice&quot;&gt;
&lt;br&gt;&lt;br&gt;&lt;br&gt;
&lt;button onclick=&quot;sum()&quot;&gt; calculate &lt;/button&gt;
&lt;h1 id=&quot;total&quot;&gt; &lt;/h1&gt; 
&lt;script src=&quot;https://ajax.googleapis.com/ajax/libs/jquery/3.6.4/jquery.min.js&quot;&gt;&lt;/script&gt;

<!-- 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(&quot;1.005.67&quot;), 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

请适当命名变量。不要使用相同的变量名和函数名,这会让读者感到困惑。

**注意:**如果将 &lt;input&gt;type 设置为 type=&quot;number&quot;,您可以设置 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 &lt;input&gt; to type=&quot;number&quot;, 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(&#39;en-US&#39;,
  { style: &#39;currency&#39;, currency: &#39;USD&#39; });

const calculateSumAndDisplay = () =&gt; {
  const sum = [...document.querySelectorAll(&#39;.totalPrice&#39;)]
    .reduce((total, input) =&gt; total + input.valueAsNumber, 0);
  document.querySelector(&#39;#total&#39;)
    .textContent = `Total: ${currencyFormatter.format(sum)}`;        
}

<!-- language: lang-html -->

&lt;label&gt;Value 1&lt;/label&gt;
&lt;input type=&quot;number&quot; class=&quot;totalPrice&quot; step=&quot;0.01&quot; /&gt;
&lt;br&gt;
&lt;label&gt;Value 2&lt;/label&gt;
&lt;input type=&quot;number&quot; class=&quot;totalPrice&quot; step=&quot;0.01&quot; /&gt;
&lt;br&gt;
&lt;button type=&quot;button&quot; onclick=&quot;calculateSumAndDisplay()&quot;&gt;Calculate&lt;/button&gt;
&lt;h1 id=&quot;total&quot;&gt;&lt;/h1&gt; 

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年4月6日 22:40:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75950814.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定