How to check a string contains only digits and one occurrence of a decimal point?

后端 未结 8 1522
一向
一向 2021-02-15 14:37

My idea is something like this but I dont know the correct code

if (mystring.matches(\"[0-9.]+\")){
  //do something here
}else{
  //do something here
}
<         


        
相关标签:
8条回答
  • 2021-02-15 15:11
    int count=0;
    For(int i=0;i<mystring.length();i++){    
        if(mystring.charAt(i) == '/.') count++;
    }
    if(count!=1) return false;
    
    0 讨论(0)
  • 2021-02-15 15:13

    Use the below RegEx its solve your proble

    1. allow 2 decimal places ( e.g 0.00 to 9.99)

      ^[0-9]{1}[.]{1}[0-9]{2}$
      
      This RegEx states:
      
      1. ^ means the string must start with this.
      2. [0-9] accept 0 to 9 digit.
      3. {1} number length is one.
      4. [.] accept next character dot.
      5. [0-9] accept 0 to 9 digit.
      6. {2} number length is one.
      
    2. allow 1 decimal places ( e.g 0.0 to 9.9)

      ^[0-9]{1}[.]{1}[0-9]{1}$
      
      This RegEx states:
      
      1. ^ means the string must start with this.
      2. [0-9] accept 0 to 9 digit.
      3. {1} number length is one.
      4. [.] accept next character dot.
      5. [0-9] accept 0 to 9 digit.
      6. {1} number length is one.
      
    0 讨论(0)
提交回复
热议问题