Javascript中的Excel ROUND函数

时间:2019-01-29 08:07:19

标签: javascript excel algorithm math rounding

我在Excel中有一个数学公式,如下所示:

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

初始值:

  • B2 = 1000
  • C2 = 0
  • B55 = 0,03

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

这是我的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算法?

1 个答案:

答案 0 :(得分:1)

在Excel中,=0.3/12的值为0.025。因此,四舍五入到小数点后两位是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

所以我们不能在.toFixed中使用JavaScript。如果我们使用另一种方法对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);
})();

因为它与此问题有关,尤其是为什么在JavaScript var result = 0.3/12;中导致0.024999999999999998的情况下,指向What Every Programmer Should Know About Floating-Point Arithmetic的链接可能会有所帮助。