Javascript regular expression for negative Numbers with decimal

前端 未结 8 1303
感动是毒
感动是毒 2021-01-05 05:20

I want to test for this input: [an optional negative sign] 2 digits [an optional . and an optional digit] like this:

-34 or -34.5333 or

相关标签:
8条回答
  • 2021-01-05 05:49

    what your regEx ( /^(-)\d{2}(.d{1})$/ ) does is:

    Start with requiring the negative and then correctly your requiring two digits, then with the "." your requiring any character, you should strict it to the symbol with "\", and finally comes one digit.

    correct example code would be:

    var str = '-34.23';
    pat=/^\-?\d{2}(\.(\d)*)?$/g;
    str.match(pat);
    

    More testable example: http://jsfiddle.net/GUFgS/1/

    use the "?" after the group to make that match an option i.e (\.\d*)?

    0 讨论(0)
  • 2021-01-05 05:51

    Try this:

    /^(-)?\d{2}(\.\d+)?$/
    
    0 讨论(0)
  • 2021-01-05 05:54

    Try this regex:

    /^-?\d{2}(\.\d+)?$/
    
    0 讨论(0)
  • 2021-01-05 05:58

    this regex matches any valid integer.

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

    you can modify this to suite your needs :

    /^-?[1-9]\d{0,1}(\.[1-9]{1})?$/
    

    this matches 2.1, 21.4, 3, 90...

    0 讨论(0)
  • 2021-01-05 06:01

    Perhaps regex is not needed.

    function validate(val){
        return isNaN(val)?false:(Math.abs(Math.floor(val)).toString().length==2);
    }
    
    0 讨论(0)
  • 2021-01-05 06:02

    You can use this regular expression:

    -?\d{2}[.]?\d*
    
    0 讨论(0)
提交回复
热议问题