Using decimal and numeric input fields in Android

IMPORTANT!
This blog has moved to http://blog.brasskazoo.com!

Say I have a measurement field in my app that takes a decimal:

android-decimal

Google’s dev guide says that floats are bad, because the embedded hardware does not have floating point number support like desktop CPUs do.

And creating objects should be avoided too, if possible, because it is an expensive operation in an environment with limited resources. Garbage collection of objects used in UI code can lead to ‘hiccups’ in the user experience too.

So if a float is out, that leaves us with double, right? The best solution appears to be this:

double value = Double.parseDouble(txtInput);

parseDouble I think is better than valueOf, since we probably don’t want to be doing any auto-unboxing.

Note: I include these lines in the layout xml to restrict the field to a single-line decimal input:

<EditText
    ....
    android:singleLine="true"
    android:inputType="numberDecimal"
    ...
/>

The inputType also sets the soft keyboard (popup keyboard) to the numeric keyboard.

Advertisements

2 responses to “Using decimal and numeric input fields in Android

  1. Thank you dude, this post cleared my doubt

  2. Thanks this tip helped a newbie android developer.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s