Question

I want to use JavaScript to restrict input on a text box to currency number formatting. For example:

<input type="text" value="2,500.00" name="rate" />

As given above, the text box should accept only numbers, commas and a period.

But, after the period it should accept two digits after numbers.

How do I accomplish this? Please clarify.

  • Gnaniyar Zubair
Was it helpful?

Solution

parseFloat can convert a string to a float and toFixed can set how many decimal places to keep.

function numToCurrency(num){
    return parseFloat(num).toFixed(2);
}


numToCurrency("4.2334546") // returns 4.23

OTHER TIPS

If you want to do validation for your textbox, you can use Regular Expressions. If you want to restrict the input from the user, you can trap the keystrokes and filter out the ones you want them to enter using the onKeyDown event of the textbox.

You could use a jQuery's plugin called Alphanumeric

jQuery AlphaNumeric is a javascript control plugin that allows you to limit what characters a user can enter on textboxes or textareas. Have fun.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top