Unexpected decimal

This is part of my code for Cash Register challenge. Can someone tell me why would i here return the value with unlimited decimals rather than just 1.3?

  **Your code so far**
  let i = 5.3
  while (i >= 2){
    i -= 2;
  }

  console.log(i)     // 1.2999999999999998
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36 Edg/94.0.992.38

Challenge: Cash Register

Link to the challenge:

It’s a result of the way numbers, specifically numbers with decimals (i.e. floating point numbers) are represented in JS. Since there are an infinite amount of floating point numbers it is impossible to represent them all accurately and JS has to approximate sometimes. One example that is used to demonstrate this is

0.1 + 0.2

Type that into the console and see what you get.

You just happened to stumble upon another approximation (45.3 - 20).

P.S. I got the 45.30 - 20 from your original code but I think you have changed it since then.

2 Likes

Floating point arithmetic has rounding errors.

I recommend using a fixed number of digits or doing the calculations in integer numbers of cents.

1 Like

I managed to get the correct i value without rounding error by using .toFixed(2)

But here when I’m trying to apply it to penny, I get TypeError: penny.toFixed is not a function

  let i = 0.5
  let penny = 0;

  while (i > 0){
    penny = penny + 0.01;
    i = i.toFixed(2) - 0.01;
  }
console.log(penny)      // 0.5000000000000002

I am not getting any errors running the code you just posted. Are you sure you posted the correct version?

1 Like

Sorry I should’ve posted the modified version. What I meant was if u do this:

  let i = 0.5
  let penny = 0;

  while (i > 0){
    penny = penny.toFixed(2) + 0.01;
    i = i.toFixed(2) - 0.01;
  }

you get TypeError: penny.toFixed is not a function

I think it has got something to do with the typeof (penny). Before .toFixed() is applied it was a number and after applying the method it becomes a string :smiley:

1 Like

Read the docs to see what the return value of toFixed is.

Ahh, I see you answered this question with your previous post.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.