August 2013
Intermediate to advanced
720 pages
16h 23m
English
You want to convert a String to
one of Scala’s numeric types.
Use the to* methods that are
available on a String (courtesy of
the StringLike trait):
scala>"100".toIntres0: Int = 100 scala>"100".toDoubleres1: Double = 100.0 scala>"100".toFloatres2: Float = 100.0 scala>"1".toLongres3: Long = 1 scala>"1".toShortres4: Short = 1 scala>"1".toByteres5: Byte = 1
Be careful, because these methods can throw the usual Java
NumberFormatException:
scala> "foo".toInt
java.lang.NumberFormatException: For input string: "foo"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java)
at java.lang.Integer.parseInt(Integer.java:449)
... more output here ...BigInt and BigDecimal instances can also be created
directly from strings (and can also throw a NumberFormatException):
scala>val b = BigInt("1")b: scala.math.BigInt = 1 scala>val b = BigDecimal("3.14159")b: scala.math.BigDecimal = 3.14159
If you need to perform calculations using bases other than
10, you’ll find the toInt method in the Scala Int class doesn’t have a method that lets
you pass in a base and radix. To solve this problem, use the parseInt method in the java.lang.Integer class, as shown in these
examples:
scala>Integer.parseInt("1", 2)res0: Int = 1 scala>Integer.parseInt("10", 2)res1: Int = 2 scala>Integer.parseInt("100", 2)res2: Int = 4 scala>Integer.parseInt("1", 8)res3: Int = 1 scala>Integer.parseInt("10", 8)res4: Int ...
Read now
Unlock full access