简体   繁体   中英

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 (ie a numeric/decimal field), what is the best way to convert it to an decimal value in the application code?

数值EditText

Google recommends avoiding float s, 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.

The reasons that using Double.parseDouble is the best solution:

  • On a normal CPU, float operations are implemented by hardware operations. This is most likely not built into a mobile CPU, and would be replaced by software operations (which are significantly slower).

  • Using static methods of Double , rather than creating an instance via new Double(txtInput) is better for memory usage as it means only the class definition is loaded into the JVM, and we never have additional overhead from state information created by an instance of Double .

  • An alternative to Double.parseDouble is Double.valueOf , but this returns an instance of Double , and then we have created an object unnecessarily since we are just unboxing it to a double primitive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM