I'm trying to format the user input values using following technique, but I get the following error on Fire Bug console
$(this).val().toFixed is not a fun开发者_StackOverflow社区ction
$(".amount-text").bind('change',function () {
$(this).val(($(this).val()).toFixed(2));
});
Can some one help me on this?
.val()
returns a string, to use .toFixed()
on a number you'll need to parse it into a Number first, like this:
$(".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()
:
$(".amount-text").bind('change',function () {
$(this).val(function(i, v) { return parseFloat(v).toFixed(2); });
});
You can give it a try here.
toFixed
only works on a number, parse the value to a number first:
$(this).val(parseFloat($(this).val()).toFixed(2));
This is because val()
returns a String
rather than a Number
. To be able to use toFixed()
, do something like:
$(".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:
$(".amount-text").bind('change',function () {
$(this).val( (0 + $(this).val()).toFixed(2) );
});
but I don't recommend it for readability purposes!
HTML5 added the property valueAsNumber
to the input
element, so you don't need to apply parseFloat
by yourself. (Documentation at MDN)
精彩评论