1

Trying to write a program that returns the exact change in coins the coins am using are [1, 0.50, 0.20, 0.10, 0.05, 0.02, 0.01]. am trying to do it using only conditional statements. my problem is that the last "IF" statement isn't working as i want it to, and i dont get what is wrong.

for example for the current number the outcome should be [1 x 0.20 and 2 x 0.02]. in place of that it is returning me [1 x 0,20 and 1 x 0.02 and 1 x 0.01]

var price = 0.76;
var paid = 1;

var a = paid - price;

var oneLeva = 0;
var fiftyCents = 0;
var twentyCents = 0;
var tenCents = 0;
var fiveCents = 0;
var twoCents = 0;
var oneCents = 0;

if((a - 1) >= 0){
  oneLeva += 1;
  a -= 1;
  if((a - 1) >= 0){
    oneLeva += 1;
    a -= 1;
    if((a - 1) >= 0){
      oneLeva += 1;
      a -= 1;
      if((a - 1) >= 0){
        oneLeva += 1;
        a -= 1;
      }  
    }  
  }  
}

if((a - 0.50) >= 0){
  fiftyCents += 1;
  a -= 0.50; 
}

if((a - 0.20) >= 0){
  twentyCents += 1;
  a -= 0.20;
  if((a - 0.20) >= 0){
    twentyCents += 1;
    a -= 0.20; 
  }  
}

if((a - 0.10) >= 0){
  tenCents += 1;
  a -= 0.10; 
}

if((a - 0.05) >= 0){
  fiveCents += 1;
  a -= 0.05;  
}

if((a - 0.02) >= 0){
  twoCents += 1;  
  a -= 0.02;  
  if((a - 0.02) >= 0){
    twoCents += 1;    
    a -= 0.02; 
  }
}

if((a - 0.01) > 0){
  oneCents += 1;
  a -= 0.01;  
}


console.log(oneLeva);
console.log(fiftyCents);
console.log(twentyCents);
console.log(tenCents);
console.log(fiveCents);
console.log(twoCents);
console.log(oneCents);
MadSorrow
  • 11
  • 1

2 Answers2

2

Welcome to doing math in JavaScript!

Alright, so, what's happening is that when you do 0.24 - 0.2, the result is NOT 0.04. Instead, it's 0.03999999999999998. You then subtract 0.02 from that which gives 0.01999999999999998, which is less than 2, so the if statements get messed up and your code gives the unexpected result.

The reason this is is because JavaScript does not store floating point numbers as most would expect, meaning it loses precision.

You can see this in action by doing console.log(a) in each step of your code.

I highly suggest you take a look at this SO post, which covers exactly the problem you are running into. There are multiple solutions that will work for you.

w3schools has some good examples too.

Have fun!

Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128
0

JS as many other programming languages works bad with floating point numbers. The workaround is simple enough: just multiply all your numbers to 100 or 1000 etc. until there is no floating point, then do you calculations, then divide back the result by 100 or 1000 etc.

Nurbol Alpysbayev
  • 19,522
  • 3
  • 54
  • 89