Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin / java - Is there something like TryParse()?

Tags:

java

kotlin

I need to convert 3 editText to Double and do an automatic calculation. The problem is: in Java, using Double.parseDouble() throw an exception if editText string is null so I have to use a try catch. In Kotlin, using toDoubleOrNull I have to check with an "if" if is null or not.

Now, with 2 editText i have to do val a = firstDobule + secondDouble and then val b = a + 2 But using aboved methods I can't separate the calculation: it need to convert all 3 editText in the same time and I want to convert a singular editText at time.

to make you understand better, this is the code in C#:

 Double.TryParse(firstEditText.Text, out Double firstDouble);
 Double.TryParse(secondEditText.Text, out Double secondDOuble);

Double a = firstDouble + secondDOuble;
Double b = a + 2;

In C#, using TryParse it doesn't throw any exception and doesn't need to check manually if is null or not. I want to do this, but in Kotlin or Java

like image 464
Arfmann Avatar asked Jan 20 '26 14:01

Arfmann


1 Answers

You can write an extension function for EditText that will return its text value as a double.

fun EditText.doubleValue() = text.toString().toDoubleOrNull() ?: 0.0

This assumes you want to get 0 in case of unparsable input. Then you can read off values easily:

val a = firstEditText.doubleValue() + secondEditText.doubleValue()
val b = a + 2
like image 146
Pawel Avatar answered Jan 23 '26 04:01

Pawel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!