Show decimals in Groovy section

I am sure this is a very simple question, but I'm stuck. I am new to Groovy.

Let's say I have:

Long percentageFee = 285   
percentageFee = percentageFee / 100     //Display as 2.85%

I tried this in several ways, dropping percentageFeeto double, etc., but the result is still only 2.

I have to get the syntax wrong or something like that.

+3
source share
3 answers

If you add a decimal place to one of the operands, then this is no longer an integer division:

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

Here 100.0 is BigDecimal.

If it was Java, then splitting the long into an integer will result in a long. But in Groovy, this does not work. The division operation returns BigDecimal, assigning the result to Long, truncates the result:

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

( blackdrag .)

+5

"Groovy", , Groovy Groovy - .

def percentageFee = 285   
percentageFee = percentageFee.div(100)
assert percentageFee == 2.85

, .

: -)

. Groovy

+1

Something like this should do this:

def percentageFee = 285.0
percentageFee = percentageFee / 100
println percentageFee

Result 2.85

0
source

All Articles