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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With