This tutorial shows you some basics use of numbers in Groovy.

Java supports primitive types and object types for all numbers types of java. Java has the wrapper classes to allow conversion from primitives to object or object to primitive. Java 5+ has the autoboxing feature to hide the conversion.

Groovy treats everything as an object at the language level and it does appropriate autoboxing under the cover when integrating with java.

BigDecimal used as the default type for non-Integers in Groovy, the operator overloading applies to all common operations on numbers, e.g. 4 * 5 is the same as 4.multiply(5)

You can use these operators for your own types, e.g. Person * 3 calls the multiple method on your person object.

Below is some example code for Number in Groovy.

package com.java.connect.groovy class GroovyNumberExample { static void main(def args) { def x = 5 def y = 6 // You can do normal add println(x + y) // This is also allowed println(x.plus(y)) // You can check the x in what instance println(x instanceof Integer) // Take the other example def a = 5/6 // Get round value def b = a.setScale(4, BigDecimal.ROUND_HALF_UP) println(b.toString()) // Add by operator println(7+8) // Add by method println(7.plus(7)) // Minus by operator println(7-6) // Minus by method println(7.minus(6)) // Multiply by operator println(4*12) // Multiply by method println(4.multiply(12)) // mod by operator println(45%35) // mod by method println(45.mod(35)) // Power by operator println(4**2) //Power by method println(4.power(2)) //Division by operator println(4/3) // Division by method println(4.div(3)) // Normal integer division println(4.intdiv(3)) } }