Why can't I use forFixed for the value of the input HTML object?

I have an HTML input element, and I'm trying to force one decimal place into the input after the user changes the value. So, let's say the user enters "4", I run this code:

this.value = this.value.toFixed(1)

but then I get a JavaScript error: "Object 4 does not have a 'toFixed' method."

JavaScript seems to be trying to treat the literal as a number and is unsuccessful, but why? And how can I avoid this?

+3
source share
2 answers

this.valueis Stringwhen you get it from an input element. You need to point it to a number before you can use numerical methods on it:

this.value = Number(this.value).toFixed(1);

+ :

this.value (+this.value).toFixed(1);

, parseFloat:

this.value = parseFloat(this.value).toFixed(1);

, parseFloat , Number :

this.value = +'0xF'; //15
this.value = parseFloat('0xF'); //0
+22

,

this.value = Number(this.value).toFixed(1);

this.value , toFixed.

+3

All Articles