bigdecimal

How to handle very large numbers in Scala (BigInt, BigDecimal)

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 2.6, “Handling Very Large Numbers in Scala.”

Problem

You’re writing a Scala 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: How to parse a number from a String

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 2.1, “Parsing a Number from a String.”

Problem

You want to convert a String to one of Scala’s numeric types (Byte, Double, Int, Float, Long, Short).

How to use BigInt and BigDecimal when you need very large numbers in Scala

Scala FAQ: I’m writing an application and I need to use very large integer or decimal (floating-point) numbers; what’s the best approach?

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:

MySQL Java mappings (Decimal to BigDecimal, etc.)

As I get back into working with a MySQL database in a Java (Scala, actually) development project and also in adding functionality to Cato, I found these MySQL to Java data type mappings, via this link:

The Play Framework, MySQL, currency, decimal fields, and BigDecimal types

I’m currently working on a Play Framework server-side application that handles money/currency. (The application UI uses Sencha ExtJS, but that doesn’t matter for this example.)

From past experience I know that this means I need to use a decimal field in my MySQL database table. (MySQL also lets you declare this field type as numeric.) I further know that the MySQL JDBC driver uses a java.math.BigDecimal field to insert and select from this field type.

How to convert from a Scala BigDecimal to Java BigDecimal

Scala FAQ: How do I convert from a Scala BigDecimal instance to a Java BigDecimal?

Call the bigDecimal method on your Scala BigDecimal instance, as shown in this example in the REPL:

scala> val sb = scala.math.BigDecimal(12345)
sb: scala.math.BigDecimal = 12345

scala> val jb = sb.bigDecimal
jb: java.math.BigDecimal = 12345

As you can see, invoking sb.bigDecimal returns a java.math.BigDecimal.

Scala money and currency - The BigDecimal class and libraries

Note: I don't have any immediate solutions in this article; it's more of a discussion of where I'm at today when looking at handling money/currency in Scala.

As a quick note, I've started to look at handling money/currency in Scala, and I'm also starting to explore a couple of money/currency libraries.