javascript 为什么不能对 HTML 输入对象的值使用 toFixed?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5330420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:50:07  来源:igfitidea点击:

Why can't I use toFixed on an HTML input object's value?

javascripthtml

提问by Jeff Chausse

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:

我有一个 HTML 输入元素,我试图在用户更改值后强制输入一个小数位。因此,假设用户输入“4”,我运行以下代码:

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

but then I get a JavaScript error saying "Object 4 has no method 'toFixed'".

但随后我收到一个 JavaScript 错误,提示“对象 4 没有‘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?

似乎 JavaScript 正试图将文字作为数字处理,但失败了,呃,为什么?我该如何避免?

回答by zzzzBov

this.valueis a Stringwhen 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.valueString,当你从一个输入元素得到它。您需要先将其转换为数字,然后才能对其使用数字的方法:

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:

如果您需要删除字符串后缀,则可以使用parseFloat

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

However, it's worth noting that parseFloatdoes nothandle hexadecimal formats while casting to Numberdoes:

然而,值得注意的是,parseFloat处理的十六进制格式,而铸造Number

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

回答by Anurag

convert to a Number first,

首先转换为数字,

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

this.valueis a String, and a string does not have the toFixedmethod.

this.value是一个字符串,而字符串没有该toFixed方法。