2

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.

Mithilesh D
  • 31
  • 1
  • 1
  • 3

1 Answers1

8

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_re-introduction_to_JavaScript#Numbers

Epoch
  • 656
  • 4
  • 16