Search code examples
android-edittextdoubletostringgettextvalue-of

How do I only retrieve numbers in an EditText instead of the whole String?


Double value = Double.valueOf(temp.getText().toString());

Let's say editText temp is 32 Celsius. I only want to get 32 instead of "32 Celsius" so how would I be able to do this? Is this possible?

I'm a newbie with Android Studio.


Solution

  • The simplest way that comes into my mind is

    Double value = Double.valueOf(temp.getText().toString().split(" ")[0]);
    

    which splits the string using the space and only takes the first value in the generated array.

    This works if the user enters something like "[any_number] [any other string, even more words]".
    i.e.: "32 Celsius", "952 years ago", "4 pieces of cake", ...