1

I would like to pass only proper currency amounts such as 22.22, 465.56, 1424242.88

I have been using this regex:

[0-9]+\.[0-9][0-9](?:[^0-9a-zA-Z\s\S\D]|$)

But it allows symbols such as £25.55. How can I force only numbers in correct currency format?

Thanks for any help

3
  • Sorry I'm not sure why it turned out like that. It should be: /[0-9]+\.[0-9][0-9](?:[^0-9]|$)/ Commented Feb 18, 2013 at 10:09
  • @ kadeshiseraph: Because you didn't mark it up. When you were typing your question, there was this handy How to Format box to the right. There was also a preview area where you could see how it would look when posted. And of course, SO showed you your own post when you clicked Post Your Question. Commented Feb 18, 2013 at 10:11
  • 1
    How about negative amounts? :) Commented Feb 18, 2013 at 10:13

1 Answer 1

1

It sounds like you just haven't provided the anchors on the regex, and you haven't escaped the .. E.g. it should be:

var currencyNumbersOnly = /^\d+\.\d{2}$/;

Breakdown:

  • ^ Start of string.

  • \d A digit (0-9).

  • + One or more of the previous entity (and so \d+ means "one or more digits").

  • \. A literal decimal point. Note that some cultures use , rather than .!

  • \d{2} Exactly two digits.

  • $ End of string.

This isn't hyper-rigorous. For instance, it allows 0000000.00. It also disallows 2 (requiring 2.00 instead). Also note that even when talking about currency figures, we don't always only go down to the hundreds. Bank exchange rates, for instance, may go on for several places to the right of the decimal point. (For instance, xe.com says that right now, 1 USD = 0.646065 GBP).

And as Jack points out in comments on the question, you may want to allow negative numbers, so throwing a -? (0 or 1 - characters) in there after the ^ may be appropriate:

var currencyNumbersOnly = /^-?\d+\.\d{2}$/;

Update: Now that I can see your full regex, you may want:

var currencyNumbersOnly = /^\d+\.\d{2}(?:[^0-9a-zA-Z\s\S\D]|$)/;

I'm not sure what you're doing with that bit at the end, especially as it seems to say (amongst other things) that you allow a single character as long as it isn't 0-9 and as long as it isn't \D. As \D means "not 0-9", it's hard to see how something could match that. (And similarly the \s and \S in there.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.