Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# BigDecimal divide question

Tariq Ahsan
Ranch Hand
Posts: 116
Hello All,

Was getting the error - "java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result" while trying to do a divide of a BigDecimal by a BigDecimal. Found some code that I used to solve this problem above. The code I have does not look pretty. Wondering if there is a easier way to do the same.
Here's the code I have -

Here's the output -

Garrett Rowe
Ranch Hand
Posts: 1296
How many decimal places do you want to represent?

Tariq Ahsan
Ranch Hand
Posts: 116
Thanks Garrett for your response. I would like to have 2 decimal places.

Tariq Ahsan
Ranch Hand
Posts: 116
Garrett,

Just tried the changes below with your code to get 2 decimal position output. Is there any other simpler way?

The output :

Garrett Rowe
Ranch Hand
Posts: 1296
This is a little simpler:

Tariq Ahsan
Ranch Hand
Posts: 116
Garrett,

Worked perfectly!

Thanks a lot!

Tariq

Tariq Ahsan
Ranch Hand
Posts: 116
Ugh...

The code did'nt quite work for me for the inputs as shown below -

Getting the output as - 78. But expect - 78.34

Any suggestions?

Thanks

Campbell Ritchie
Sheriff
Posts: 50273
80
Read the MathContext specification. The 2 appears to refer to significant figures, not places after the decimal point.

Tariq Ahsan
Ranch Hand
Posts: 116
Any idea if I want to have result to be with 2 decimal points? Eventually I have to store the output value in NUMBER(9,2) datatype column in a database table.

Thanks

Campbell Ritchie
Sheriff
Posts: 50273
80
There are several overloaded divide methods. Have you been through them? Are they of any use? Note what "scale" means.

Tariq Ahsan
Ranch Hand
Posts: 116
So far, the code below is working for me. But again need to try out exhaustively with all kinds of decimal value combinations.

Getting 78.34 as expected

Tariq Ahsan
Ranch Hand
Posts: 116
Or better use -

Was getting 79.02 with CEILING. With HALF_EVEN getting the correct result - 79.01. For the num with 1.16 getting the expected 78.34.