Hi all, I'm having some problems using BigDecimal...
# getting-started
j
Hi all, I'm having some problems using BigDecimal, I'm not sure if I'm missing anything or there is some issues with the toBigDecimal() method. I'm trying to create an expected value to validate a business logic. I'm trying the expected value to be a big decimal equals to 100.00 (note 2 decimal places). The problem is that I cannot get this amount; it always come as 100.0 (a single decimal place, which make the assert to fail) Here is a snippet code that shows the issue: https://pl.kotl.in/O8tUt3IxC
Sorry, I clicked send before writing the whole message. What I really wanted was a break line but sent the message 🙂. I have updated the message to include the issue I'm having!
e
not really Kotlin-specific, since the classes involved all come from Java, but
Copy code
DecimalFormat("#,##0.00").format(decimal)
might do what you want, although note this formatting will always round to a nearest 0.01 even if you have more precision
n
you might also be looking for BigDecimal#setScale https://pl.kotl.in/yf8_wlcl5
👍 1
the DecimalFormat approach is for if you're trying to render to a string in a particular way, while setScale will configure (a copy of) the BigDecimal itself
e
you can also directly construct
Copy code
BigDecimal(10000.toBigInteger(), 2) == 100.toBigDecimal().setScale(2)
👍 1
j
Thanks, I will take a look to scale. I'm working on a service/API contract for monetary amounts so it goes beyond rendering. I'm coming from Groovy and its sugar made this type of things easy but I'm not giving up Kotlin yet!
n
I'm not super familiar with currency-specific libraries for Java/Kotlin, but BigDecimal might be all you need
j
Thanks all, it is solved. I've included the scale and rounding mode when overloading the operators for BigDecimals (/,*...) and in in the expected values from the tests. Thanks!