Monday 15 April 2019

javascript - Sum of float and int returns unusual decimal places js

I have written a code for a certain project of mine where i am adding a couple of numbers. In the process, i add integers and floats from an array. Until the last element of the array, the sum has a proper number of decimal places. But at the last element, the sum suddenly gives me a lot of decimal places. The number adding to the previous sum and the sum itself have less than 3 decimal places, yet the final sum has more than 3 decimal places. Here's the code. It's in JS.



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]]);


Here's the result



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


Here as you can see, the sum of 235.41 and 100 gives 335.4099999...
I know I can round it off using toFixed function. However, I'm looking to understand why it happens like this.




Forgive me if my English is raw or if i'm asking a stupid question, I'm a beginner from a third world country and just want to learn.

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...