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

后端 未结 8 1530
一向
一向 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:09

    I think using regexes complicates the answer. A simpler approach is to use indexOf() and substring():

    int index = mystring.indexOf(".");
    if(index != -1) {
        // Contains a decimal point
        if (mystring.substring(index + 1).indexOf(".") == -1) {
            // Contains only one decimal points
        } else {
            // Contains more than one decimal point 
        }
    }
    else {
        // Contains no decimal points 
    }
    

提交回复
热议问题