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?

2
  • 3
    Does this answer your question? How do I convert a Char to Int? Commented Mar 27, 2020 at 4:27
  • @DrawnRacoon no Commented Mar 27, 2020 at 11:32

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

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.