1

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
Bjorn
  • 69,215
  • 39
  • 136
  • 164
Gnaniyar Zubair
  • 8,114
  • 23
  • 61
  • 72

4 Answers4

2

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
Bjorn
  • 69,215
  • 39
  • 136
  • 164
Zach
  • 24,496
  • 9
  • 43
  • 50
  • Hi Zech, Thanks for your instance coding. i will try it out. - Gnaniyar Zubair – Gnaniyar Zubair Apr 30 '09 at 04:52
  • This actually doesn't do what your question originally intended... but could be merged into a more complete answer. I'll leave it up if it's useful. – Zach Apr 30 '09 at 04:57
1

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.

Kirtan
  • 21,295
  • 6
  • 46
  • 61
0

These jQuery plugins can help..

http://www.texotela.co.uk/code/jquery/numeric/

http://plugins.jquery.com/project/aphanumeric

Vijay Dev
  • 26,966
  • 21
  • 76
  • 96
0

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.

eKek0
  • 23,005
  • 25
  • 91
  • 119