Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 409
C.S Avatar asked Sep 16 '25 05:09

C.S


2 Answers

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
like image 111
Xavier Guihot Avatar answered Sep 17 '25 20:09

Xavier Guihot


You can do this:

val a = 10
val b = BigDecimal(0.1000000000001)
a * b

res0: scala.math.BigDecimal = 1.0000000000010

As you can see you don´t lose precision

like image 32
Pedro Correia Luís Avatar answered Sep 17 '25 20:09

Pedro Correia Luís