要保留小数点两位,可以使用toFixed()方法来实现。在计算income和cost时,使用toFixed(2)来保留两位小数。修改后的代码如下:

caltaxExemptIncome() {
  const income = parseFloat(this.form.income ? this.form.income.toString().replace(',', '') : 0).toFixed(2);
  const cost = parseFloat(this.form.cost ? this.form.cost.toString().replace(',', '') : 0).toFixed(2);
  const taxExemptIncome = ((income - cost) * 0.3).toFixed(2);
  
  this.form.taxExemptIncome = parseFloat(taxExemptIncome);
  this.form.cost = this.calculateCost(income);
},

calculateCost(income) {
  if (income <= 4000) {
    return 800;
  } else {
    return (income * 0.2).toFixed(2);
  }
}

在这个修改后的代码中,income和cost都使用了toFixed(2)来保留两位小数。

JavaScript 保留小数点两位:优化收入和成本计算

原文地址: https://www.cveoy.top/t/topic/plaL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录