Can anyone help me understand what I'm doing wrong?
#JS #accessibility #learningToCode #learningToProgram #beginnerProgrammer #beginnerCoder #JavaScriptIsHard
Tell us what’s happening: My code is failing tests 18 and 19. I used console.log statements to figure out why, and it’s returning INSUFFICIENT-FUNDS for test 18. I’ve gone over my code but have no idea why. Can someone help me figure this out? Your code so far <!DOCTYPE html> <html lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale = 1.0" /> <meta charset="UTF-8" /> <title>freeCodeCamp Cash Register Project</title> </head> <body> <h1>Cash Re...
@RareBird_15 Ohhh thats an nasty bug that you stumpled onto here, so let me explain.
First lets insert some debug statements to check whats going on: We'll add some console.log statements in the calculateChange function, about after the cash === price if, and print out the following:
totalCid + pricetotalCidchangeIf you now enter any value (like 2 for example), you'll get this in your console:
337.28000000000003
335.41
0.1299999999999999
Whats that enourmous (broken) looking numbers you might ask. That's an infamous bug when you work with floating point numbers. Floats have an precision; if you make calculations that involve something that goes beyond the precision, weird things happens. For example; just execute this line: 0.1 + 0.2, which every sane human being would say is 0.3 but computers instead produce 0.30000000000000004.
The same thing is happening to you here; since the total sum of your cid would equal to 337.28 in an calculator, computer-math instead results in 337.28000000000003. If you plug in that number instead, you'll see that it indeed responds with the correct output.
An article for further informations on that topic can be found here: https://jvns.ca/blog/2023/02/08/why-does-0-1-plus-0-2-equal-0-30000000000000004/ (Only the first one I've got of from google, there should be plenty others available, just search after "float precision" and "float rounding bugs" etc.)
Also, here's my jsbin with the log statements already applied: https://jsbin.com/kenodulowu/edit?js,console,output
@RareBird_15 Sadly no, because .toFixed returns an string, and you can't mathematically work with them, unless you'll use parseFloat to make a number out of them again, but then we're back at square one xD
An tip: the problematic part is the fractional part of the number :3