Simple regular expression for a decimal with a precision of 2

后端 未结 17 2022
闹比i
闹比i 2020-11-22 02:02

What is the regular expression for a decimal with a precision of 2?

Valid examples:

123.12
2
56754
92929292929292.12
0.21
3.1
相关标签:
17条回答
  • 2020-11-22 02:51

    This will allow decimal with exponentiation and upto 2 digits ,

    ^[+-]?\d+(\.\d{2}([eE](-[1-9]([0-9]*)?|[+]?\d+))?)?$
    

    Demo

    0 讨论(0)
  • 2020-11-22 02:52

    Valid regex tokens vary by implementation. A generic form is:

    [0-9]+(\.[0-9][0-9]?)?
    

    More compact:

    \d+(\.\d{1,2})?
    

    Both assume that both have at least one digit before and one after the decimal place.

    To require that the whole string is a number of this form, wrap the expression in start and end tags such as (in Perl's form):

    ^\d+(\.\d{1,2})?$
    

    To match numbers without a leading digit before the decimal (.12) and whole numbers having a trailing period (12.) while excluding input of a single period (.), try the following:

    ^(\d+(\.\d{0,2})?|\.?\d{1,2})$
    

    Added

    Wrapped the fractional portion in ()? to make it optional. Be aware that this excludes forms such as 12. Including that would be more like ^\d+\\.?\d{0,2}$.

    Added

    Use ^\d{1,6}(\.\d{1,2})?$ to stop repetition and give a restriction to whole part of the decimal value.

    0 讨论(0)
  • 2020-11-22 02:52
    preg_match("/^-?\d+[\.]?\d\d$/", $sum)
    
    0 讨论(0)
  • 2020-11-22 02:56

    For numbers that don't have a thousands separator, I like this simple, compact regex:

    \d+(\.\d{2})?|\.\d{2}
    

    or, to not be limited to a precision of 2:

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

    The latter matches
    1
    100
    100.
    100.74
    100.7
    0.7
    .7
    .72

    And it doesn't match empty string (like \d*.?\d* would)

    0 讨论(0)
  • 2020-11-22 02:58

    In general, i.e. unlimited decimal places:

    ^-?(([1-9]\d*)|0)(.0*[1-9](0*[1-9])*)?$.

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