Sum of float and int returns unusual decimal places js
我已经为我的某个项目编写了一个代码,我在其中添加了几个数字。在这个过程中,我从数组中添加整数和浮点数。在数组的最后一个元素之前,和的小数位数是正确的。但在最后一个元素,和突然给了我很多小数位。加在前一个和上的数字和本身的小数位数小于3位,而最后一个和的小数位数大于3位。这是密码。在JS中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | function checkCashRegister(price, cash, cid) { var change = 0, cidSum = 0; change = cash - price; console.log(change); console.log(cid.length); for ( var i = 0; i < cid.length; i++ ){ console.log("number" + cid[i][1]); cidSum += cid[i][1]; console.log("sum" + cidSum); } console.log(cidSum); // Here is your change, ma'am. return change; } // Example cash-in-drawer array: // [["PENNY", 1.01], // ["NICKEL", 2.05], // ["DIME", 3.10], // ["QUARTER", 4.25], // ["ONE", 90.00], // ["FIVE", 55.00], // ["TEN", 20.00], // ["TWENTY", 60.00], // ["ONE HUNDRED", 100.00]] checkCashRegister(19.50, 20.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]); |
结果如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 0.5 9 number 1.01 sum 1.01 number 2.05 sum 3.0599999999999996 number 3.1 sum 6.16 number 4.25 sum 10.41 number 90 sum 100.41 number 55 sum 155.41 number 20 sum 175.41 number 60 sum 235.41 number 100 sum 335.40999999999997 335.40999999999997 |
号
如你所见,235.41和100的总和为335.40999999…我知道我可以用tofixed函数把它四舍五入。不过,我想知道为什么会这样。
如果我的英语不好,或者我问了一个愚蠢的问题,请原谅我,我是一个来自第三世界国家的初学者,我只想学习。
1 2 3 | let x = 0.1 + 0.2; // 0.30000000000000004 x = parseFloat(x.toFixed(2)); // Number of places, rounded. console.log(x); // 0.3 |
Numbers in JavaScript are"double-precision 64-bit format IEEE 754
values", according to the spec. This has some interesting
consequences. There's no such thing as an integer in JavaScript, so
you have to be a little careful with your arithmetic if you're used to
math in C or Java.Also, watch out for stuff like:
0.1 + 0.2 == 0.30000000000000004; In practice, integer values are treated as 32-bit ints, and some implementations even store it that
way until they are asked to perform an instruction that's valid on a
Number but not on a 32-bit integer. This can be important for bit-wise
operations.
号
https://developer.mozilla.org/en-us/docs/web/javascript/a_重新介绍_javascript