Check if there is a comma and replace it with a period

2

I have an EditText where I pick up what was entered in the box and I am trying to verify if it introduced commas, letters where only a format like this is allowed: 123.11

If the user enters the parameter other than a value of type Float the application is broken. And I do not know how to avoid it.

    
asked by Eduardo 27.05.2017 в 19:10
source

3 answers

5

Although recently I'm programming with android I think you can prevent the user from entering letters or commas by applying android:inputType="numberDecimal" in the EditText you want.

An example:

    <EditText
       android:id="@+id/editxt_loquesea"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:inputType="numberDecimal" />

I hope it serves you!

    
answered by 27.05.2017 / 19:19
source
2
public double getValor(String texto){
    if(texto.contains(",")){
        return Double.parseDouble(texto.replace(",", ".").trim());
    }
    return Double.parseDouble(texto.trim());
}

The function receives as a parameter the value as a String, and first we verify if that String contains commas.

If you have them, then replace the commas of the string with a point and return that value to double.

In the case that it does not have commas, then it only returns the value of the parameter converting it to double.

    
answered by 27.05.2017 в 20:19
1
public void afterTextChanged(Editable s) {
    double doubleValue = 0;
    if (s != null) {
        try {
            doubleValue = Double.parseDouble(s.toString().replace(',', '.'));
        } catch (NumberFormatException e) {
            //Error
        }
    }
    //Hacer cualquier cosa con el doblevalue
}

With this function, as you can see, substitute commas with points, so you should not have any problems.

    
answered by 27.05.2017 в 19:20