currency

Scala number, date, and formatting examples

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 format numbers and currency in Scala

Scala FAQ: How can I format numbers and currency in Scala, such as to control the number of decimal places and commas in the values, typically for printed output.

Basic formatting

For basic number formatting, use the f string interpolator shown in Recipe 1.4 of the Scala Cookbook, “Substituting Variables into Strings”:

scala> val pi = scala.math.Pi
pi: Double = 3.141592653589793

scala> println(f"$pi%1.5f")
3.14159

A few more examples demonstrate the technique:

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.

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.

A Java DecimalFormat example

Here's a quick example of how to use the Java DecimalFormat class to format float and double numbers for output, such as printing information in a currency format.

The example below creates a simple DecimalFormat that is similar to a U.S. currency format. As you can see from the for loop, it begins printing at 100, and prints decimal numbers up to a value of just over 1,000: