Converting from a text field to an numeric in Android

If I have an EditText component on my screen that I have specified inputType="decimal" for (i.e. a numeric/decimal field), what is the best way to convert it to an decimal value in the application code?

Numeric EditText

Google recommends avoiding floats, and avoiding creating objects unnecessarily (and I assume any auto-unboxing code is bad too), so I take these as my constraints. I realise a small application probably doesn’t need to worry too much, but I haven’t been able to find a ‘best-practice’ solution to this.

The most common solution appears to be this:

double value = Double.parseDouble(txtInput);


That is the best solution, you should also check for “NumberFormatException” exceptions, just incase of non valid charecters. Then return feedback to the user if it’s wrong.

If you don’t want floats, your going to have to look at fixed point arthimetic. The reason they want you to avoid using float is because it’s rarely implemented on phone cpu’s(Probbly arm), and has to be implemented in software which is slow. Fixed point is usally surported in hardware.

Leave a Reply

Your email address will not be published. Required fields are marked *