0

I have the following code:

newCode = "9780802412720"
val character = newCode[0]
val charInt = character.toInt()

What I'm expecting is that chatInt == 9, but what's happening is that charInt == 57 instead. Why?

Here's a screenshot from Android Studio while debugging. Where is that 57 coming from?

enter image description here

2 Answers 2

4

You'll have to convert your Char to a String in order to convert it to a Digit. Otherwise, you will get the integer used to represent the Char internally.

UPDATE: If you are using Kotlin 1.5 or higher

Kotlin 1.5 introduced Char.digitToInt(), which does this conversion for you. You can even specify the radix, but it conveniently defaults to base 10.

character.digitToInt()

Before Kotlin 1.5

character.toString().toInt()

And you could define an extension function to make this cleaner:

fun Char.asDigit(): Int = this.toString().toInt()
println(character.asDigit())
Sign up to request clarification or add additional context in comments.

Comments

4

57 is the Ascii code for the character 9.

To get the value 9 you need to use:

newCode[i] - '0'

This works because the Ascii digit characters are right next to each other in ascending order '0' is 48. In many languages, including Kotlin, the Characters are just numbers so basic mathematical operations work as normal.

2 Comments

This seems like a simple solution taking leverage of Kt types, it would be good to explain how this work
More accurately and precisely, 57 is the UTF-16 value for the UTF-16 code unit '9'.

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.