Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 38 ยท Language Basics

Numbers and Math in Groovy

Understand Groovy numeric types: automatic promotion, BigDecimal literals, the power operator, integer division with intdiv, number suffixes, number methods and rounding.

Numbers in Groovy follow rules that are friendlier than Java's for everyday math, and a little different from what Java programmers expect. Decimal literals are exact, division of two integers gives a decimal, and there is a power operator. This lesson explains the numeric types, the arithmetic operators, helpful number methods and how to round correctly.

Groovy blocks are read-only here. Where the idea is easier to see in running code, a Java stand-in with BigDecimal is provided, because BigDecimal behaves the same in both languages.

Integer types and automatic promotion

Whole-number literals pick the smallest type that fits: Integer, then Long, then BigInteger.

GROOVY
println 42.class                       // class java.lang.Integer
println 3000000000.class               // class java.lang.Long
println 100000000000000000000.class    // class java.math.BigInteger

Arithmetic keeps results exact. Multiplying two large integers promotes to a bigger type rather than overflowing silently as Java's int would:

GROOVY
def big = Integer.MAX_VALUE * 2
println big          // 4294967294 (a Long), no overflow

You can force a type with a suffix: 10L (Long), 10G (BigInteger), 10I (Integer). Literals also accept underscores for readability and several bases:

GROOVY
def million = 1_000_000
def hex = 0xFF           // 255
def bin = 0b1010         // 10
def oct = 017            // 15

Decimals are BigDecimal

A decimal literal such as 1.5 is a BigDecimal. That makes everyday decimal math behave the way people expect:

GROOVY
println 0.1 + 0.2        // 0.3
println 1.1 * 3          // 3.3

With double in Java (or with 0.1d + 0.2d in Groovy), the result is 0.30000000000000004, because binary floating point cannot represent 0.1 exactly. Suffixes select other types: 1.5d or 1.5D for double, 1.5f for float, 1.5g for BigDecimal explicitly.

The Java stand-in below prints the same contrast. BigDecimal is the class Groovy uses for decimal literals.

Java Java stand-in: BigDecimal versus double

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Division

In Groovy, dividing two integers with / does not truncate:

GROOVY
println 7 / 2         // 3.5
println 1 / 2         // 0.5
println 6 / 3         // 2
println 1 / 3         // 0.3333333333

The result is a BigDecimal. When the division is not exact, Groovy keeps at least ten digits after the point. For the integer quotient use intdiv:

GROOVY
println 7.intdiv(2)    // 3
println 7 % 2          // 1 (remainder)

For positive numbers intdiv is plain floor division.

The % operator gives the remainder, and mod() gives a non-negative result for a positive divisor:

GROOVY
assert 7 % 3 == 1
assert 7.mod(3) == 1

The power operator

Groovy has ** for exponents, and **= to update a variable:

GROOVY
println 2 ** 10       // 1024
println 2 ** 0.5      // 1.4142135623730951 (a double)
println 2 ** -1       // 0.5
def n = 3
n **= 2               // n is 9

An integer raised to a non-negative integer power stays an integer type and promotes when needed, so 2 ** 100 is an exact BigInteger. This is useful for factorials and other number theory tasks.

Operators and shortcuts

Operator Meaning
+ - * / Arithmetic; / yields BigDecimal for integers
% Remainder
** Power
++ -- Increment, decrement
+= -= *= /= %= **= Compound assignment
<=> Compare (-1, 0, 1)

Comparing numbers of different types with == works as you expect: 1 == 1.0 is true. Underlying types are promoted before the comparison.

Number methods from the GDK

Numbers have helper methods that read like English:

GROOVY
3.times { print it }                // prints 012
1.upto(4) { print it }              // 1234
10.downto(7) { print it }           // 10987
0.step(10, 5) { print "$it " }      // 0 5 10
println 10.abs()                    // 10
println((-10).abs())                 // 10
println 3.7.round()                 // 4
println 3.14159.round(2)            // 3.14

times, upto, downto and step replace Java for loops for simple counting. Because 0.step(10, 5) includes the end value 10, it prints three numbers.

Rounding and formatting

round() gives the nearest integer, round(n) rounds to n decimal places, and Math.floor/Math.ceil work as in Java. To format a number for display, use String.format or printf:

GROOVY
def price = 1234.5
println String.format('%,.2f', price)   // 1,234.50
printf('%05d%n', 42)                    // 00042
println Math.sqrt(144)                  // 12.0
println Math.PI.round(4)                // 3.1416

Money should use BigDecimal with an explicit RoundingMode:

Java Java stand-in: rounding money with BigDecimal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

In Groovy the same calculation reads naturally with operators, because BigDecimal supports +, -, * and / directly:

GROOVY
def net = 19.99 * 3
def tax = (net * 0.0825).setScale(2, java.math.RoundingMode.HALF_UP)
println net + tax

Math class and conversions

Math and java.lang.Number methods are all available: Math.abs, Math.pow, Math.max, Math.min, Math.sqrt. To convert text to numbers use '12'.toInteger(), '12'.toLong(), '1.5'.toBigDecimal() or '1.5'.toDouble(). Check input first with '12'.isInteger() or 'x'.isNumber().

GROOVY
def input = '42'
if (input.isInteger()) {
    println input.toInteger() * 2     // 84
}

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the type of the literal 2.5 in Groovy?

    Groovy decimal literals are BigDecimal, which is why 0.1 + 0.2 equals 0.3 exactly.
  2. 2. What does 7 / 2 evaluate to in Groovy?

    Groovy's / on integers returns a BigDecimal when the division is not exact. Use intdiv for the integer quotient.
  3. 3. How do you compute 3 to the power of 4?

    ** is the power operator. ^ is bitwise XOR in Groovy, as in Java.
  4. 4. Which suffix makes a number a double?

    d or D means double. G is BigInteger/BigDecimal, L is Long and I is Integer.

Summary

  • Integers promote automatically (Integer, Long, BigInteger) so they rarely overflow.
  • Decimal literals are exact BigDecimal values; use d for double.
  • / on integers gives a decimal; intdiv gives the whole-number quotient; ** is power.
  • times, upto, downto and step make counting loops short.
  • Use BigDecimal with an explicit rounding mode for money.

Next: Strings and GStrings