Show decimals in Groovy division

division, groovy, math

Solution

If you add a decimal place to either one of the operands then it isn't integer division anymore:

groovy:000> percentageFee = 285L
===> 285
groovy:000> percentageFee / 100.0
===> 2.85

Here 100.0 is a BigDecimal.

If this was Java then dividing a long with an integer would result in a long. But in Groovy it doesn't work like that. The division operation returns a BigDecimal, assigning the result to a Long truncates the result:

groovy:000> percentageFee = 285L
===> 285
groovy:000> f = percentageFee / 100
===> 2.85
groovy:000> f.class
===> class java.math.BigDecimal

(Thanks to blackdrag for the clarification.)

Problem

I'm sure this is a very simple question but I'm stuck. I'm new to Groovy. Let's say I have: ``` Long percentageFee = 285 percentageFee = percentageFee / 100 //Display as 2.85% ``` I've tried this several ways, casting `percentageFee` to `double`, etc, but the result is still just 2. I must be getting the syntax wrong or something.

Original source