我在 Excel 中有一个数学公式,如下所示:
ROUND((B2+C2)*(B55/100)/12;2)
初始值:
- B2 = 1000
- C2 = 0
- B55 = 0,03
这是我的 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);
})();
因为和这个问题有关,特别是为什么在JavaScript
中var 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/