简体   繁体   中英

Getting a Double value from an EditText

I want to input a numeric value into an EditText box. The InputType is specified as "numberDecimal|numberSigned". The code I've found that works is:

mLatitude = txtLatitude.text.toString().toDouble()

This seems unnecessarily convoluted. Can it really be necessary to convert first to a string then to a double? Is there an easier way?

Double.parseDouble() would not accept Editable that is returned by txtLatitude.text.

You can create your own extension if you want

fun Editable.toDouble() = toString().toDouble()

fun test() {
    mLatitude = txtLatitude.text.toDouble()
}

There is no another way. For convenience you can create an extension function on EditText :

fun EditText.getDouble(): Double = try {
    text.toString().toDouble()
} catch (e: NumberFormatException) {
    e.printStackTrace()
    0.0
}

And use it like this:

val latitude = editText.getDouble()

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