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 function
$(".amount-text").bind('change',function () {
$(this).val(($(this).val()).toFixed(2));
});
Can some one help me on this?
The toFixed() method in JavaScript is used to format a number using fixed-point notation. It can be used to format a number with a specific number of digits to the right of the decimal. The toFixed() method is used with a number as shown in above syntax using the '. ' operator.
Description. In JavaScript, toFixed() is a Number method that is used to convert a number to fixed-point notation (rounding the result where necessary) and return its value as a string. Because toFixed() is a method of the Number object, it must be invoked through a particular instance of the Number class.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With