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

后端 未结 8 1531
一向
一向 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 14:56

    You could use indexOf() and lastIndexOf() :

    int first = str.indexOf(".");
    if ( (first >= 0) && (first - str.lastIndexOf(".")) == 0) {
        // only one decimal point
    }
    else {
        // no decimal point or more than one decimal point
    }
    

提交回复
热议问题