有没有一种方法可以在模板字符串中四舍五入到2位小数

Is there a way to round to 2 decimals in a template string?

本文关键字:字符串 四舍五入 小数 2位 一种 方法 有没有      更新时间:2023-09-26

如何转换我的getPriceWithOrWithoutDiscount以确保它只显示2位小数。必须用所有小数进行计算,以确保正确

var getTotalPriceAfterDiscount = 0;
products.forEach(function (product) {
  var occurence = cart.getOccurenceOfProduct(product.id);
  getTotalPriceAfterDiscount += occurence * cart.getPriceWithOrWithoutDiscount(product.id);
}
var output;
output += `
           <tr>
                <th colspan="2">Discount:</th>
                <td>'u20AC ${Math.round(getTotalPriceAfterDiscount)}</td>
           </tr>
          `;

Math.round在模板字符串中不起作用

使用toFixed(n)方法(n为小数位数):

getTotalPriceAfterDiscount.toFixed(2);