Search code examples
scalabigdecimal

Multiply a BigDecimal with an Integer


I want to multiply a financial amount with a quantity. I know Scala uses Java's BigDecimal under the hood but the syntax doesn't seem to be the same.

val price = BigDecimal("0.01") // £0.01
val qty   = 10

I tried to do this

BigDecimal(price).*(BigDecimal(qty))

But it's a compile error. If I look at the Java SO posts you can pass integer into BigDecimal and then multiply it like this

BigDecimal(price).multiply(BigDecimal(qty))

So how do you do this in Scala? And are there any dangers in losing precision by multiplying a decimal and integer like this? I will need sum a lot of these together as well


Solution

  • You can actually multiply a BigDecimal with an Int using BigDecimal's multiplication operator:

    def *(that: BigDecimal): BigDecimal

    since the Int you will provide as its parameter will be implicitly converted to a BigDecimal based on:

    implicit def int2bigDecimal(i: Int): BigDecimal


    You can thus safely multiply your BigDecimal with an Int as if it was a BigDecimal and receive a BigDecimal with no loss in precision:

    val price = BigDecimal("0.01")
    // scala.math.BigDecimal = 0.01
    val qty   = 10
    // Int = 10
    price * qty // same as BigDecimal("0.01").*(10)
    // scala.math.BigDecimal = 0.10