Numbers and BigDecimal
Groovy reads a decimal literal as a java.math.BigDecimal, not as a double. The first example of every floating point talk therefore prints the honest answer here:
Decimal literals are exact
money.groovy
def price = 0.1 + 0.2
println price
println(price == 0.3)
println price.getClass().name
groovy money.groovy
0.3
true
java.math.BigDecimal
A Java double cannot hold 0.1 exactly, which is why the same sum in Java is 0.30000000000000004. Groovy pays for the exactness with arithmetic that is slower than a machine float, and chooses it anyway: a script that handles money should not start with a rounding error.
Division of two integers
division.groovy
println 7 / 2
println 7.intdiv(2)
println 7 % 2
println 2 ** 10
println 10.0 / 3
groovy division.groovy
3.5
3
1
1024
3.3333333333
/ on two integers gives a decimal, because Groovy widens the result instead of truncating it. intdiv is the integer division a Java programmer expects, and % keeps the remainder. The last line shows the scale of the default decimal division: ten digits after the point.
Suffixes and conversions
A suffix asks for another type: L for Long, f for Float, d for Double, g or G for BigDecimal and I for BigInteger. Without one, an integer literal is an Integer or a Long when it does not fit.
suffixes.groovy
println 10L.getClass().name
println 1.5f.getClass().name
println 2.5d.getClass().name
println 2.5g.getClass().name
println 10I.getClass().name
println '42'.toInteger() + 1
println '3.14'.toBigDecimal() * 2
groovy suffixes.groovy
java.lang.Long
java.lang.Float
java.lang.Double
java.math.BigDecimal
java.lang.Integer
43
6.28
Rounding a money value
round.groovy
def total = 10.0 / 3
println total
println total.round(2)
println total.setScale(2, BigDecimal.ROUND_HALF_UP)
println total.round(new java.math.MathContext(3))
groovy round.groovy
3.3333333333
3.33
3.33
3.33
round(2) keeps two decimals, setScale chooses the rounding mode, and a MathContext limits the number of significant digits. A price is a BigDecimal with a scale, never a double.
Related
- Operators: the arithmetic signs in the company of the Groovy shorthand.
- Strings and GStrings: how a number reaches a message.
Article author: Arthur Isaev