2.2. Converting Between Numeric Types (Casting)
Problem
You want to convert from one numeric type to another, such as from
an Int to a Double.
Solution
Instead of using the “cast” approach in Java, use the to* methods that are available on all numeric
types. These methods can be demonstrated in the REPL (note that you need
to hit Tab at the end of the first example):
scala>val b = a.to[Tab]toByte toChar toDouble toFloat toInt toLong toShort toString scala>19.45.toIntres0: Int = 19 scala>19.toFloatres1: Float = 19.0 scala>19.toDoubleres2: Double = 19.0 scala>19.toLongres3: Long = 19 scala>val b = a.toFloatb: Float = 1945.0
Discussion
In Java, you convert from one numeric type to another by casting the types, like this:
inta=(int)100.00;
But in Scala, you use the to*
methods, as shown in this recipe.
If you want to avoid potential conversion errors when casting from
one numeric type to another, you can use the related isValid methods to test whether the type can
be converted before attempting the conversion. For instance, a Double object (via RichDouble) has methods like isValidInt and isValidShort:
scala>val a = 1000La: Long = 1000 scala>a.isValidByteres0: Boolean = false scala>a.isValidShortres1: Boolean = true
See Also
The RichDouble class |
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access