javascript - Javascript 中的 Excel ROUND 函数

标签 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 算法?

最佳答案

在 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,链接到What Every Programmer Should Know About Floating-Point Arithmetic可能会有帮助。

关于javascript - Javascript 中的 Excel ROUND 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54416408/

相关文章:

javascript - Bootstrap 工具提示/弹出窗口关闭导致 HTML 元素被隐藏

javascript - 数组中的所有对总和为 10,具有平均/最佳 O(n) 运行时复杂度

javascript - 如何删除嵌套数组中存在名称属性未定义的 JSON 对象

arrays - 查找节点在数组中的位置(作为二进制堆)

c - 检查matrix[1000][1000]中重复元素的解决方法

javascript - 处理从 javascript 到 MySQL 到 javascript 到 MS SQL 到 javascript 的时区

excel - 如何在不使用NA()的情况下强制Excel图表跳过0?或通过 IF 返回 "empty"

vba - Excel 按名称打印工作表

excel - COUNTIFS 大于 TODAY 或空白单元格

perl - 如何根据年龄删除 Perl 散列或数组项?