2.1. Parsing a Number from a String
Problem
You want to convert a String
to
one of Scala’s numeric types.
Solution
Use the to*
methods that are
available on a String
(courtesy of
the StringLike
trait):
scala>"100".toInt
res0: Int = 100 scala>"100".toDouble
res1: Double = 100.0 scala>"100".toFloat
res2: Float = 100.0 scala>"1".toLong
res3: Long = 1 scala>"1".toShort
res4: Short = 1 scala>"1".toByte
res5: 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
Handling a base and radix
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 ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.