Scala number, date, and formatting examples alvin February 27, 2018 - 10:15pm

This short blog post contains a collection of Scala number and date examples. I created most of these in the process of writing the Scala Cookbook. Unlike the Cookbook, I don’t describe the examples here much at all, I just show the examples, mostly as a reference for myself (and anyone else that can benefit from them).

Scala numeric types

Scala has these numeric types:

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?


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:

How to convert between numeric types in Scala

Scala FAQ: How do I convert between numeric types in Scala, such as from Int to Long, Int to Double, etc.?


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):

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.

Perl array/sort FAQ - Perl integer array sorting

Summary: How to sort Perl arrays, in this case, a Perl integer array.

Sorting a Perl integer array (technically a Perl numeric array) is relatively simple, well, at least once you know the magic formula. The key thing to know is that you need to provide the Perl sort function a helper function (or block of code) that tells it how to sort integers. By default, the Perl sort function sorts arrays in ASCII order, and that's not going to work very well for you.