Reputation: 461
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?
Upvotes: 0
Views: 247
Reputation: 461
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])) }
Upvotes: 0
Reputation: 152817
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()
.
Upvotes: 2