Groovy — Variables, integer division, and formatting
In Groovy, intdiv gives the integer quotient and the remainder operator gives the units left over. Use both to display an integer price in cents as dollars and cents.
A simple example
Change a stored number
- Start with n starts at 2
- Do this Add 1 to n
- Result 3
int n = 2
n++
println(n)
3
Calculate a receipt in cents
Groovy can infer types with def, but declaring the monetary quantities as int makes the units clear. intdiv performs integer division. The ordinary division operator has different number semantics.
A student buys three notebooks at 125 cents each. Add the 50-cent delivery charge once for the whole order. Keeping the arithmetic in cents makes the total easy to check against the receipt.
Run the example
Groovy 4 on the JVM. Run these commands from the directory containing the example.
groovy Lesson.groovy
int priceCents = 125
int quantity = 3
int total = priceCents * quantity + 50
printf('%d.%02d%n', total.intdiv(100), total % 100)
4.25
Three items at 125 cents cost 375 cents. Adding one 50-cent delivery charge gives 425 cents. The quotient and remainder on division by 100 give 4 dollars and 25 cents.
Try it yourself
What happens if each item costs 101 cents?
Check your answer
Three items plus delivery cost 353 cents, so the output becomes 3.53.