Can't increase by 0.1 with `toFixed(1)` in JavaScript

Viewed 289

I'm trying to create two methods: one for increasing the number by 0.1 and another one for decreasing by the same value. But I met an unexpected behavior for me: I can decrease the number properly using number = (number - 0.1).toFixed(1);, but when I'm trying to increase the number the same way (it works only once), I've got the error:

"Uncaught TypeError: (number + 0.1).toFixed is not a function"

Here is the code:

var number = 0.5;
console.log('Number: ', number)

function increase() {
  if (number < 1) {
    number = (number + 0.1).toFixed(1);
    console.log('Number: ', number)
  }
}

function decrease() {
  if (number > 0) {
    number = (number - 0.1).toFixed(1);
    console.log('Number: ', number)
  }
}
<button onclick="increase()">Increase</button>
<button onclick="decrease()">Decrease</button>

My question is: Why? And how should I correct my code, to repair my increase method?

Thanks in advance

2 Answers

The toFixed() method returns a string type, and string don't have a toFixed() method - resulting in the error of .toFixed is not a function.

To resolve, force the output from toFixed() back to a number. This can be done with Number() or the shorthand method of prepending +.

  • Number((0.1).toFixed())
  • +(0.1).toFixed()

var number = 0.5;
console.log('Number: ', number)

function increase() {
  if (number < 1) {
    number = Number((number + 0.1).toFixed(1));
    console.log('Number: ', number)
  }
}

function decrease() {
  if (number > 0) {
    number = Number((number - 0.1).toFixed(1));
    console.log('Number: ', number)
  }
}
<button onclick="increase()">Increase</button>
<button onclick="decrease()">Decrease</button>

The return value of toFixed method is a string, as mentioned in MDN web docs:

Return value: A string representing the given number using fixed-point notation.

So, when calling increase or decrease for the first time, the value of the variable number will be of type string.

After that when calling increase:

number + 0.1 will be of type string, because string + number is a string, and toFixed is not a function of strings, and that's why you get the error:

Uncaught TypeError: (number + 0.1).toFixed is not a function

However, number - 0.1 will work, because string - number is a number and that's fine.

To solve this, you should keep your number of type number, and you can do this in multiple ways:

number = parseFloat((number + 0.1).toFixed(1));

  • Use Number object constructor:

number = Number((number + 0.1).toFixed(1));

  • Use +:

number = +((number + 0.1).toFixed(1));

Related