Excel Javascript 中的 ROUND 函数

Excel ROUND function in Javascript

我在Excel中得到了一个数学公式,如下:

ROUND((B2+C2)*(B55/100)/12;2)

初始值:

结果(t 表示以月为单位的时间)。

这是我的 Javascript 方法:

(function _calculateRates() {
  var singlePayment = parseInt(1000, 10),
    amount = singlePayment,
    monthlyPayment = parseInt(0, 10),
    investTime = parseFloat(12),
    rate_a = parseFloat(0.03),
    rate_b = parseFloat(0.03),
    investment = monthlyPayment,
    interest = 0;

  for (var month = 0; month < investTime; month += 1) {
    investment = (month === 0) ? 0 : monthlyPayment;

    interest = Number(((amount + investment) * (rate_a / 100) / 12).toFixed(2));
    amount = Number((amount + interest + investment).toFixed(2));
  }
  console.log('Result: ', amount);
})();

可以看出,结果不正确。

在哪里可以找到 ROUND() 的 Microsoft Excel 算法?

在 Excel 中 =0.3/12 的计算结果为 0.025。所以四舍五入到 2 位小数是 0.03

在 JavaScript var result = 0.3/12; 中得到 0.024999999999999998.toFixed(2)0.02.

内部 Excel 也像所有使用 IEEE Standard for Floating-Point Arithmetic (IEEE 754) 的系统一样获得 0.024999999999999998。但它有附加规则,最多只能取 15 位数字。即0.02499999999999 + 0.000000000000009,也就是0.025.

所以我们不能在JavaScript中使用.toFixed。如果我们在 JavaScript 中使用另一种舍入方法,这将导致与 Excel.

中相同的结果

查看使用简单值的示例:

var result = 0.3/12;
console.log(result);
console.log(result.toFixed(2));
console.log(Math.floor((Math.pow(10, 2)*result)+0.5)*Math.pow(10, -2));

查看使用您的算法的示例:

(function _calculateRates() {
  var singlePayment = parseInt(1000, 10),
    amount = singlePayment,
    monthlyPayment = parseInt(0, 10),
    investTime = parseFloat(12),
    rate_a = parseFloat(0.03),
    rate_b = parseFloat(0.03),
    investment = monthlyPayment,
    interest = 0;

  for (var month = 0; month < investTime; month += 1) {
    investment = (month === 0) ? 0 : monthlyPayment;

    interest = Number(((amount + investment) * (rate_a / 100) / 12));
    interest = Math.floor((Math.pow(10, 2)*interest)+0.5)*Math.pow(10, -2);
    amount = Number((amount + interest + investment));
    amount = Math.floor((Math.pow(10, 2)*amount)+0.5)*Math.pow(10, -2);
  }
  console.log('Result: ', amount);
})();

因为它与这个问题有关,特别是为什么在JavaScriptvar result = 0.3/12;导致0.024999999999999998,所以link到What Every Programmer Should Know About Floating-Point Arithmetic可能会有所帮助。