Scala FAQ: How do I convert between numeric data types in Scala, such as from Int
to Long
, Int
to Double
, etc.?
Solution
Instead of using the “cast” approach in Java, use the to*
methods that are available on all of Scala’s numeric types. These methods can be demonstrated in the REPL (note that you need to hit the [Tab] key at the end of the first example):
scala> val b = a.to[Tab] toByte toChar toDouble toFloat toInt toLong toShort toString scala> 19.45.toInt res0: Int = 19 scala> 19.toFloat res1: Float = 19.0 scala> 19.toDouble res2: Double = 19.0 scala> 19.toLong res3: Long = 19 scala> val b = a.toFloat b: Float = 1945.0
Discussion
In Java, you convert from one numeric type to another by casting the types, like this:
int a = (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 = 1000L a: Long = 1000 scala> a.isValidByte res0: Boolean = false scala> a.isValidShort res1: Boolean = true
this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |