Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert String obtained from edittext to Integer in Kotlin language

Tags:

kotlin

I am trying to make a simple Android application using Kotlin language. I have one EditText, I am getting its value in String but I want to convert that value into an integer. How can I convert this string to integer in Kotlin language?.

like image 413
Manish Singh Rana Avatar asked Jun 30 '17 08:06

Manish Singh Rana


People also ask

How can I change text to int in Android Studio?

The Best Answer is you have to used. String value= et. getText(). toString(); int finalValue=Integer.

How do I get text from string in Kotlin?

To get substring of a String in Kotlin, use String. subSequence() method.


2 Answers

The above is the general idea but here is a syntax straight out of Android Studio, from a different tutorial I'm doing.

Note that the compiler was perfectly happy to do a cast of a cast.

var myNewInt: Int = myEditTextView.text.toString().toInt()
like image 147
scottstoll2017 Avatar answered Sep 30 '22 10:09

scottstoll2017


You can use .toInt():

val myNumber: Int = "25".toInt()

Note that it throws a NumberFormatException if the content of the String is not a valid integer.

If you don't like this behavior, you can use .toIntOrNull() instead (since Kotlin 1.1):

val myNumOrNull: Int? = "25".toIntOrNull()
like image 37
zsmb13 Avatar answered Sep 30 '22 09:09

zsmb13