Groovy - Using Numbers

[Last Updated: Nov 9, 2018]

We have already seen in a previous tutorial that Groovy converts all primitive types to their corresponding Number wrapper types.

In this tutorial we will go through some additional features associated with Numbers.

Automatic Transformation of BigDecimal and BigInteger

In Java, to initialize BigInteger or BigDecimal, we have to use their one of the constructors or the static factory methods (e.g. valueOf(...)).

Groovy allows to directly initialize these object by assigning them with an appropriate literal value.


BigDecimal bd = 1.3
println bd
BigInteger bi = 3
println bi



Default types

If we don't use a specific type and instead use def then Groovy chooses a default type itself.

In case of an integral, the default type can be one of Integer, Long or BigInteger, depending on the capacity of the type that can hold the provided integral number.

In case of decimal, the default type is always BigDecimal.


//integral default values
def i = 1;
println i.getClass().getName()

def j = 2147483648;//Integer.MAX_VALUE+1
println j.getClass().getName()

def k =  9223372036854775808;// Long.MAX_VALUE+1
println k.getClass().getName()

//decimal default values
def d = 4.1
println d.getClass().getName()



Number type suffixes

While using def, we can force a variable to have a specific type by providing a suffix to the provided value. Some of the suffixes are already defined by Java specification which are:
L or l for long,
F or f for float and
D or d for double.

Groovy provides more suffixes which are:
I or i for integers and
G or g for either BigInteger or BigDecimal depending on whether the provided value is integral or decimal.`



//integral types
def i = 2
println "2 = ${i.getClass().getName()}"

def a = 2G
println "2G = ${a.getClass().getName()}"

def b = 2L
println "2L = ${b.getClass().getName()}"

def c = 2I
println "2I = ${c.getClass().getName()}"


2 = java.lang.Integer
2G = java.math.BigInteger
2L = java.lang.Long
2I = java.lang.Integer


//decimal types
def i = 2.1
println "2.1 = ${i.getClass().getName()}"

def a = 2.1G
println "2.1G = ${a.getClass().getName()}"

def b = 2.1D
println "2.1D = ${b.getClass().getName()}"

def c = 2.1F
println "2.1F = ${c.getClass().getName()}"

//non fractional values
def d = 2D
println "2D = ${d.getClass().getName()}"

def e = 2F
println "2F = ${e.getClass().getName()}"


2.1 = java.math.BigDecimal
2.1G = java.math.BigDecimal
2.1D = java.lang.Double
2.1F = java.lang.Float
2D = java.lang.Double
2F = java.lang.Float

Example Project

Dependencies and Technologies Used:

  • Groovy 2.5.3
  • JDK 9.0.1
Groovy - Using Numbers Select All Download
  • groovy-numbers
    • src
      • IntegralTypeSuffixes.groovy

    See Also