Javascript toFixed() 不是函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3725192/
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
Javascript toFixed() is not a function
提问by SLM
I'm trying to format the user input values using following technique, but I get the following error on Fire Bug console
我正在尝试使用以下技术格式化用户输入值,但在 Fire Bug 控制台上出现以下错误
$(this).val().toFixed is not a function
$(this).val().toFixed 不是函数
$(".amount-text").bind('change',function () {
$(this).val(($(this).val()).toFixed(2));
});
Can some one help me on this?
有人可以帮助我吗?
回答by Nick Craver
.val()
returns a string, to use .toFixed()
on a number you'll need to parse it into a Number first, like this:
.val()
返回一个字符串,要.toFixed()
在数字上使用,您需要先将其解析为数字,如下所示:
$(".amount-text").bind('change',function () {
$(this).val(parseFloat($(this).val()).toFixed(2));
});
Or with jQuery 1.4+, a bit cleaner, at least to me use a function with .val()
:
或者使用 jQuery 1.4+,更简洁一点,至少对我来说使用一个函数.val()
:
$(".amount-text").bind('change',function () {
$(this).val(function(i, v) { return parseFloat(v).toFixed(2); });
});
回答by djdd87
toFixed
only works on a number, parse the value to a number first:
toFixed
仅适用于数字,首先将值解析为数字:
$(this).val(parseFloat($(this).val()).toFixed(2));
回答by DMI
This is because val()
returns a String
rather than a Number
. To be able to use toFixed()
, do something like:
这是因为val()
返回 aString
而不是 a Number
。为了能够使用toFixed()
,请执行以下操作:
$(".amount-text").bind('change',function () {
$(this).val( (parseFloat($(this).val())).toFixed(2) );
});
or even:
甚至:
$(".amount-text").bind('change',function () {
$(this).val( (new Number($(this).val())).toFixed(2) );
});
You may also be able to do it slightly more hackily as:
您也可以稍微更hackily地执行以下操作:
$(".amount-text").bind('change',function () {
$(this).val( (0 + $(this).val()).toFixed(2) );
});
but I don't recommend it for readability purposes!
但出于可读性目的,我不推荐它!
回答by Rainald62
HTML5 added the property valueAsNumber
to the input
element, so you don't need to apply parseFloat
by yourself. (Documentation at MDN)
HTML5valueAsNumber
给input
元素添加了属性,所以你不需要parseFloat
自己去申请。(MDN 上的文档)