The available numeric types and their declarations in Groovy were introduced in section 3.1. You have seen that for decimal numbers, the default type isjava.math.BigDecimal . This is a feature to get around the most common misconceptions about floating-point arithmetic. We’re going to look at which type is used where and what extra abilities have been provided for numbers in the GDK.
Coercion with numeric operators:
It is always important to understand what happens when you use one of the numeric operators. Most of the rules for the addition, multiplication, and subtraction operators are the same as in Java, but there are some changes regarding floating-point behavior, and BigInteger and java.math.BigDecimal also need to be included. The rules are straightforward. The first rule to match the situation is used.
For the operations + , - , and * :
Table 3.9 depicts the scheme for quick lookup. Types are abbreviated by uppercase letters.
Rules can be daunting without examples, so this behavior is demonstrated in table 3.10.
In Java, results like in the fourth row are often surprising—for example, (1/2) is always zero because when both operands of division are integers, only integer division is performed. To get 0.5 in Java, you need to write (1f/2).
GDK methods for numbers:
The GDK defines all applicable methods from table 3.4 to implement overridable operators for numbers such as plus , minus , power , and so forth. They all work without surprises. In addition, the abs, toInteger , and round methods do what you’d expect.
More interestingly, the GDK also defines the methods times , upto, downto , and step. They all take a closure argument. Listing 3.9 shows these methods in action: timesis just for repetition, upto is for walking a sequence of increasing numbers, downto is for decreasing numbers, and step is the general version that walks until the end value by successively adding a step width.
- Listing 3.9 GDK methods on numbers