Question

I have this jQuery code:

$('#amount').change(function() {
  $('#amount').val( $('#amount').val().toFixed(2) );
}); // end .change()

I need it to format the input in decmial format. Can it be done in jquery?

Example: In a text box,

if I enter 5 I want the value to be shown as 5.00

if I enter 5.1 I want the value to be shown as 5.10

if I enter 5.12 I want the value to be shown as 5.12

seems to be a simple need. I have to be missing something because I cannot imagine that javascript or jquery does not provide a function to do this.

Was it helpful?

Solution

An elements value is always a string, and toFixed only works on numbers, so you have to convert the value to a number before you run toFixed on it

$('#amount').on('change', function() {
    this.value = parseFloat(this.value).toFixed(2);
});

FIDDLE

OTHER TIPS

Use this as the base:

Math.round(num * 100) / 100

So your code will be:

$('#amount').change(function() {
    $('#amount').val( Math.round($('#amount').val() * 100) / 100 );
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top