Ethan Allen
Ethan Allen

Reputation: 14845

Why it Kotlin giving me the wrong Int value when converting from a String

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

Upvotes: 0

Views: 543

Answers (2)

Todd
Todd

Reputation: 31720

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

Upvotes: 4

Ge3ng
Ge3ng

Reputation: 2430

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.

Upvotes: 4

Related Questions