Simple regular expression for a decimal with a precision of 2

后端 未结 17 2075
闹比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:36
    ^[0-9]+(\.([0-9]{1,2})?)?$
    

    Will make things like 12. accepted. This is not what is commonly accepted but if in case you need to be “flexible”, that is one way to go. And of course [0-9] can be replaced with \d, but I guess it’s more readable this way.

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

    To include an optional minus sign and to disallow numbers like 015 (which can be mistaken for octal numbers) write:

    -?(0|([1-9]\d*))(\.\d+)?
    
    0 讨论(0)
  • 2020-11-22 02:39

    Won't you need to take the e in e666.76 into account?

    With

    (e|0-9)\d*\d.\d{1,2)
    
    0 讨论(0)
  • 2020-11-22 02:40

    Main answer is WRONG because it valids 5. or 5, inputs

    this code handle it (but in my example negative numbers are forbidden):

    /^[0-9]+([.,][0-9]{1,2})?$/;
    

    results are bellow:

    true => "0" / true => "0.00" / true => "0.0" / true => "0,00" / true => "0,0" / true => "1,2" true => "1.1"/ true => "1" / true => "100" true => "100.00"/ true => "100.0" / true => "1.11" / true => "1,11"/ false => "-5" / false => "-0.00" / true => "101" / false => "0.00.0" / true => "0.000" / true => "000.25" / false => ".25" / true => "100.01" / true => "100.2" / true => "00" / false => "5." / false => "6," / true => "82" / true => "81,3" / true => "7" / true => "7.654"

    0 讨论(0)
  • 2020-11-22 02:40
     function DecimalNumberValidation() {
            var amounttext = ;
                if (!(/^[-+]?\d*\.?\d*$/.test(document.getElementById('txtRemittanceNumber').value))){
                alert('Please enter only numbers into amount textbox.')
                }
                else
                {
                alert('Right Number');
                }
        }
    

    function will validate any decimal number weather number has decimal places or not, it will say "Right Number" other wise "Please enter only numbers into amount textbox." alert message will come up.

    Thanks... :)

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

    I use this one for up to two decimal places:
    (^(\+|\-)(0|([1-9][0-9]*))(\.[0-9]{1,2})?$)|(^(0{0,1}|([1-9][0-9]*))(\.[0-9]{1,2})?$) passes:
    .25
    0.25
    10.25
    +0.25

    doesn't pass:
    -.25
    01.25
    1.
    1.256

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