Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala conversion of Strings

Tags:

scala

When I run the following program :

object Problem {
  def main(args: Array[String]) = {
    val v = 53.toString
    val w = v(0).toInt
    println(w)
  }
}

it prints out 53, instead of what I would have expected, 5. Can someone help me understand why?

UPDATE: The same thing happens if I use charAt instead of the array syntax

like image 671
Amir Afghani Avatar asked Jun 04 '26 00:06

Amir Afghani


1 Answers

53 is the ASCII value for the character '5'. Try 63.toString and you'll see 54 after v(0).toInt.

Use .asDigit to convert a Char to its Int value. In other words, '5'.toInt == 53 but '5'.asDigit == 5.

like image 94
jwvh Avatar answered Jun 08 '26 01:06

jwvh