0
fun main(){
    val num=348597
    println(num.toString()[0].toInt())
}

I should be getting 3 as the output but I'm getting 51 instead.

Does anyone know why, or what I can do instead to get 3 as the result?

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
Kali
  • 421
  • 1
  • 4
  • 5

2 Answers2

2

num.toString() gives you "348597". Taking [0] from it returns the first Char '3' which is a 16-bit unicode character value. Calling toInt() just converts the character value to an integer. In unicode the codepoints < 128 are the same as in ASCII and 51 is the value for the character '3'.

To get the character as a string representing "3", change toInt() to toString().

laalto
  • 150,114
  • 66
  • 286
  • 303
0

Yo, I found the easy way how to solve this problem. I was getting 51 because I was converting char to int directly and it was returning ASCII value or shit instead. So here is the code:

fun main(){
val num=348597
//use Character.getNumericValue() instead

println(Character.getNumericValue(num.toString()[0])) }

I found the answer here.

Kali
  • 421
  • 1
  • 4
  • 5