Skip to content Skip to sidebar Skip to footer

How To Default An EditText To Integer But Allow Decimal Input?

I am using an EditText to allow a user to input a value that is stored in a Double. However, by default, Doubles look like '0.0' and it's a little annoying for a user to backspace

Solution 1:

To achieve this you can use NumberFormat

    EditText yourEditText = (EditText) findViewById(R.id.editTextID);
    //dummy data, will have user's value
    double aDouble = 4.0;

    //formats to show decimal
    NumberFormat formatter = new DecimalFormat("#0");

    //this will show "4"
    yourEditText.setText(formatter.format(aDouble));

Make sure to validate the user's input. Also, this will only modify what is displayed and not the value itself.


Solution 2:

  1. Parsing Double to String, then String to Int:

    String stringparsed = YourDouble + "";
    int intparsed = Integer.parseInt(stringparsed);
    
  2. Using substring to cut the string from a startIndex to finalIndex:

    String stringparsed = YourDouble + "";
    String final = stringparsed.substring(0,1);   //for example, if the double was    0.0, the result is 0
    

Post a Comment for "How To Default An EditText To Integer But Allow Decimal Input?"