regex for integer or floating point number with two decimals

前端 未结 2 1802
暗喜
暗喜 2020-12-10 18:52

I want to validate my currency field with regex. I want to allow the following pattern entries

1.23
1
.45
0.56
56.00

No comma should be a

相关标签:
2条回答
  • 2020-12-10 19:15

    Use \d* instead of \d+ before the decimal to match zero or more digits. Also add anchors (^ and $) or else it will pass as long as there is any match available. This would also validate an empty string, so if necessary you can use a lookahead to make sure there is at least one digit:

    ^(?=.*\d)\d*(?:\.\d\d)?$
    
    0 讨论(0)
  • 2020-12-10 19:20

    Regexes for floating-point numbers are a solved problem:

    \d*\.?\d+
    

    For at least two decimals:

    (\d*\.\d)?\d+
    

    To make it more comprehensible:

    \d+|\d*\.\d{2,}
    

    And for exactly two decimals:

    \d+|\d*\.\d{2}
    

    Depending on your language, don't forget to anchor the expression so that it must match the whole string.

    0 讨论(0)
提交回复
热议问题