0
  let price = 1
  for (let i = 0; i < 10; i++) {
    price = price + 0.00001;
    price = parseFloat(price).toFixed(5);
    console.log(price);
  }

The output will be:

1.00001
1.00001
1.00001
1.00001
1.00001
1.00001
1.00001
1.00001
1.00001
1.00001

While I would expect incremental decimal steps.

What is going on?

Daniel Martinez
  • 459
  • 3
  • 13
  • 2
    `price` is a string after the first loop. – Nina Scholz Nov 21 '21 at 10:18
  • 1
    After your first iteration, `price` is a string (due to `.toFixed()`), and `"1.00001" + 0.00001` will result in `'1.000010.00001'`, which when parsed to a number will be `1.00001` – Nick Parsons Nov 21 '21 at 10:19
  • This is why I don't use `parseFloat` (and don't use `parseInt` if I can avoid it), they both stop at the first invalid character rather than failing. So `parseFloat("1.000011.00001")` is `1.000011` rather than an error. Instead, I use unary `+` (or `Number`) with a pre-check for an empty string. More in my answer [here](https://stackoverflow.com/questions/28994839/why-does-string-to-number-comparison-work-in-javascript/28994875#28994875). – T.J. Crowder Nov 21 '21 at 10:35

1 Answers1

1

Because price is from type a string. you have to cast or parsed before you make the addition.

 price = 1
  for (let i = 0; i < 10; i++) {
    price = (parseFloat(price) + 0.00001);
    price = parseFloat(price).toFixed(5);
    console.log(price);
  }
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79