Joby Kurian
Joby Kurian

Reputation: 3937

Format a textbox like "0.00"

How to format a textbox like "0.00" using jQuery or JavaScript? If I enter value 59, then it should become 59.00. If I enter value as 59.20, then it should be the same.

Upvotes: 0

Views: 2875

Answers (1)

TM.
TM.

Reputation: 111057

With jQuery, assuming you have an input like this:

<input type="text" id="someInput" name="something"/>

You can use this:

$('#someInput').blur(function() {
    var floatValue = parseFloat(this.value);
    if (!isNaN(floatValue)) { // make sure they actually entered a number
        this.value = floatValue.toFixed(2);
    }
});

Whenever the input loses focus, the value will be converted always have 2 decimal places, as long as the user entered something that can be parsed into a number.

Upvotes: 7

Related Questions