Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript toFixed() is not a function

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?

like image 878
SLM Avatar asked Sep 16 '10 09:09

SLM


People also ask

How do I use toFixed in JavaScript?

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.

What is toFixed function?

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.


1 Answers

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!

like image 128
DMI Avatar answered Oct 06 '22 00:10

DMI