Pregunta

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.

¿Fue útil?

Solución

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.)

Otros consejos

You can also do this in a more "Groovy" way, taking advantage of what makes Groovy so groovy -- dynamically typed variables.

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

This may not fit your specific situation and is not as concise or simple as adding a decimal and a zero.

:-)

See the Groovy Goodness

Something like this should do it:

def percentageFee = 285.0
percentageFee = percentageFee / 100
println percentageFee

Result is 2.85

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top