Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How to check if an entered value is currency. Preferably by regular expression or php function.

(values like 1550.50, 1500 or 100.75)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
206 views
Welcome To Ask or Share your Answers For Others

1 Answer

I guess what you really want is a way to tell any number from a number that makes sense as a currency value. So 1.04e-7 probably shouldn't match, and neither should 1.234 or 12.3, even though all are of course numeric.

Finally, you'd have to expect thousands separators like 1,234.56 (which, like the decimal point, might also vary between locales). So, assuming that you only ever want to check currency values using the dot as decimal separator and the comma as an optional thousands separator, try this:

/d{1,3}(?:,?d{3})*(?:.d{2})?/

Explanation:

      # word boundary assertion
d{1,3} # 1-3 digits
(?:     # followed by this group...
 ,?     # an optional comma
 d{3}  # exactly three digits
)*      # ...any number of times
(?:     # followed by this group...
 .     # a literal dot
 d{2}  # exactly two digits
)?      # ...zero or one times
      # word boundary assertion

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...