How to format a text input as a decimal in jquery

2019-08-10 08:39发布

问题:

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.

回答1:

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



回答2:

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 );
});