views:

334

answers:

1

What use is the division operator on a scala BigDecimal?

val d1 = BigDecimal(2)
val d2 = BigDecimal(3)
val div = d1 / d2 //throws ArithmeticException: non-terminating decimal expansion

In order to get this to work, you need to define a DECIMAL128 context on the decimals. Unfortunately the only way I can see of doing this is:

val div = new BigDecimal(d1.bigDecimal.divide(d2.bigDecimal, MathContext.DECIMAL128)) //OK!

But this is just a mess! Am I missing something?

+7  A: 

This is a known bug in Scala -> see Ticket #1812. Apparently, it is fixed in Scala 2.8. You can also download a fix from the bug report which implements a BigDecimal with a MathContext attached to it. Using the given Decimal.scala, I can write something like this and get it to run without error:

val d1 = Decimal128(1)
val d2 = Decimal128(3)
val d3 = d1 / d2 // works, gives a truncated result

Therefore, you could either compile the given Decimal.scala file and add it to your classpath or wait for Scala 2.8, which will already have it in the standard library.

EDIT See revision 18021 of the Scala standard library for the changes to BigDecimal implementing this.

Hope it helps :)

-- Flaviu Cipcigan

Flaviu Cipcigan
That's a great answer, thanks Flaviu
oxbow_lakes