views:

86

answers:

1

Hi

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 same....How it possible ....

+1  A: 

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.

TM
Thank you.........
Joby Kurian
`isFinite` is not enough, it will wrongly return `true` with an empty string or a string containing only white-space characters (since both coerce to `0`), e.g.: `isFinite('') == true;`, `isFinite('\t\n ') == true`, for those cases, the input will end with `'NaN'` as value.
CMS
@CMS Ah, I will revert it back to my earlier version of the answer then: `parseFloat` first, then check `isNaN`.
TM