2.6. Handling Very Large Numbers
Problem
You’re writing an application and need to use very large integer or decimal numbers.
Solution
Use the Scala BigInt
and
BigDecimal
classes. You can create a
BigInt
:
scala> var b = BigInt(1234567890)
b: scala.math.BigInt = 1234567890
or a BigDecimal
:
scala> var b = BigDecimal(123456.789)
b: scala.math.BigDecimal = 123456.789
Unlike their Java equivalents, these classes support all the operators you’re used to using with numeric types:
scala>b + b
res0: scala.math.BigInt = 2469135780 scala>b * b
res1: scala.math.BigInt = 1524157875019052100 scala>b += 1
scala>println(b)
1234567891
You can convert them to other numeric types:
scala>b.toInt
res2: Int = 1234567891 scala>b.toLong
res3: Long = 1234567891 scala>b.toFloat
res4: Float = 1.23456794E9 scala>b.toDouble
res5: Double = 1.234567891E9
To help avoid errors, you can also test them first to see if they can be converted to other numeric types:
scala>b.isValidByte
res6: Boolean = false scala>b.isValidChar
res7: Boolean = false scala>b.isValidShort
res8: Boolean = false scala>if (b.isValidInt) b.toInt
res9: AnyVal = 1234567890
Discussion
Although the Scala BigInt
and
BigDecimal
classes are backed by the
Java BigInteger
and BigDecimal
classes, they are simpler to use
than their Java counterparts. As you can see in the examples, they work
just like other numeric types, and they’re also mutable (as you saw in
the +=
example). These are nice
improvements over the Java classes.
Before using BigInt
or
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.