how to extract numeric values from input string in java

后端 未结 15 1995
说谎
说谎 2020-12-13 16:25

How can I extract only the numeric values from the input string?

For example, the input string may be like this:

String str=\"abc d 1234567890pqr 548         


        
15条回答
  •  庸人自扰
    2020-12-13 16:49

     public static String convertBudgetStringToPriceInteger(String budget) {
        if (!AndroidUtils.isEmpty(budget) && !"0".equalsIgnoreCase(budget)) {
            double numbers = getNumericFromString(budget);
            if( budget.contains("Crore") ){
                numbers= numbers* 10000000;
            }else if(budget.contains("Lac")){
                numbers= numbers* 100000;
            }
            return removeTrailingZeroesFromDouble(numbers);
        }else{
            return "0";
        }
    }
    

    Get numeric value from alphanumeric string

     public static double getNumericFromString(String string){
        try {
            if(!AndroidUtils.isEmpty(string)){
                String commaRemovedString = string.replaceAll(",","");
                return Double.parseDouble(commaRemovedString.replaceAll("[A-z]+$", ""));
                /*return Double.parseDouble(string.replaceAll("[^[0-9]+[.[0-9]]*]", "").trim());*/
    
            }
        }catch (NumberFormatException e){
            e.printStackTrace();
        }
        return 0;
    }
    

    For eg . If i pass 1.5 lac or 15,0000 or 15 Crores then we can get numeric value from these fucntion . We can customize string according to our needs. For eg. Result would be 150000 in case of 1.5 Lac

提交回复
热议问题