Go from String to Float (Read well) [closed]

-2

Good friends, I need to pass a string string to float in JAVA . The problem is that in the end, each string ends with units (volt,%, cm, m .. etc)

example: Convert the String "0.22V" to float : 0.22

Thank you very much!

PS: All the Strings I want to transform are on the left and their corresponding units on the right. It is not feasible to split each one, since it would be inefficient since the +30 data is in a collection in which I must iterate.

I would greatly appreciate your help, thank you.

    
asked by Cristian Dos ramos 13.08.2017 в 18:53
source

1 answer

1

You can use the following method which extracts the decimal number from the string and stores it in a new string, finally converting it to float when you have already found all the numbers.

public float stringToFloat(String string){
    String newString="";
    for(int i=0;i<string.length();i++){
        ///Este if extrae digitos del 0 al 9 y el punto.
        if(string.charAt(i)>=48 && 
        string.charAt(i)<=57 || 
        string.charAt(i)=='.'){
        newString+=string.charAt(i);
        }
        ///se termina el ciclo cuando encuentra el primer carácter no válido, ejemplos la V de volts.
        else{
            break;
        }
    }
    return Float.parseFloat(newString);  ///Finalmente convierte la nueva cadena a float.
}
    
answered by 13.08.2017 в 19:12