17

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?.

1

3 Answers 3

30

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()
Sign up to request clarification or add additional context in comments.

Comments

25

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()

Comments

2

the returned value of (edittext.text) in kotlin is a editable? value and at the first you must convert that to string

edittext.text.toString().toInt()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.