Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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

like image 663
Commercial Suicide Avatar asked Dec 14 '25 17:12

Commercial Suicide


1 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>
like image 128
Brett DeWoody Avatar answered Dec 16 '25 08:12

Brett DeWoody



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!