简体   繁体   English

如何在 javascript 中添加购物车中的数字并正确显示小数点后的数字

[英]How can I add numbers as in a shopping cart in javascript and display them properly with the numbers after the decimal points

please help me, in JavaScript how can I add multiple numbers as like in an ecommerce shopping cart and display the numbers after the decimal point properly?请帮助我,在 JavaScript 中,如何像在电子商务购物车中一样添加多个数字并正确显示小数点后的数字? If the attribute value data-price is 2.50, I would like to display the value as 2.50 on the balance.innerHTML, not as 2.5 as it appears.如果属性值 data-price 为 2.50,我想在 balance.innerHTML 上将该值显示为 2.50,而不是显示为 2.5。 Here is my code:这是我的代码:

  <div class="row">

  <div class="col6">
  2,50$
  <div  onclick="addC(this)" data-price="2.50">
  Add to cart
  </div>
  </div>


  <div class="col6">
  2,40$
 <div onclick="addC(this)" data-price="2.40">
 Add to cart
 </div>
 </div>

 </div>

 <div id="balance" data-price="0">0</div>
function addC(product){

let balance = document.getElementById('balance');

balance.innerHTML = parseFloat(Number(balance.innerHTML).toFixed(2)) + parseFloat(Number(product.getAttribute('data-price')).toFixed(3));

}

In this method, can you please tell me, since I am using numbers with decimal points, how can I show them with the zeros, two digits after the decimal point.在这种方法中,你能告诉我,因为我使用带小数点的数字,我怎样才能用零显示它们,小数点后两位数。 I want to display them as 2,50 and 2,40 and sum them, but the current output is 2.5 and 2.4 on the DOM:我想将它们显示为 2,50 和 2,40 并将它们相加,但当前 output 在 DOM 上是 2.5 和 2.4:

在此处输入图像描述

Use toFixed on the final sum rather than on the addends.对最终总和而不是加数使用toFixed

(2.4 + 2.5).toFixed(2)  --> yields "3.30"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM