为什么我不能使用toFixed在HTML输入对象的值上? [英] Why can't I use toFixed on an HTML input object's value?
问题描述
我有一个HTML输入元素,我试图在用户更改值后强制输入一个小数位。所以,假设用户输入4,我运行这段代码:
this.value = this.value.toFixed 1)
但是我得到一个JavaScript错误,提示Object 4 has no method'toFixed'。
似乎JavaScript正在试图将一个文字处理为一个数字并且失败,但呃,为什么?如何避免它?
this.value
是一个字符串
当你从一个输入元素获得它时。您需要将其转换为数字,然后才能使用数字的方法:
this.value = Number(this。值).toFixed(1);
或者,您可以使用一元 +
运算符将字符串强制转换为数字:
this.value(+ this.value).toFixed(1);
如果您需要删除字符串后缀,则可以使用 parseFloat
:
this.value = parseFloat(this.value).toFixed(1);
然而值得注意的是 parseFloat
不会处理十六进制格式,而转换为数字
不会:
this.value = +'0xF'; // 15
this.value = parseFloat('0xF'); // 0
I have an HTML input element and I'm trying to force a single 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 saying "Object 4 has no method 'toFixed'".
It seems like JavaScript is trying to process a literal as a Number and failing but, er, why? And how do I avoid it?
this.value
is a String
when you get it from an input element. You need to cast it to a number before you can use a number's methods on it:
this.value = Number(this.value).toFixed(1);
Alternatively you can use the unary +
operator to cast the string to a number:
this.value (+this.value).toFixed(1);
If you need to remove string suffixes, then you could use parseFloat
:
this.value = parseFloat(this.value).toFixed(1);
However, it's worth noting that parseFloat
does not handle hexadecimal formats while casting to Number
does:
this.value = +'0xF'; //15
this.value = parseFloat('0xF'); //0
这篇关于为什么我不能使用toFixed在HTML输入对象的值上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!