Groovy Goodness: Truncate And Round BigDecimal Values
In Groovy 2.5.0, the round and truncate methods are added to the BigDecimal class. Here is how to use them!
Join the DZone community and get the full member experience.
Join For FreeGroovy 2.5.0 adds the round
and truncate
methods to the BigDecimal
class, which were already available on the Double
and Float
classes. These methods can take an argument to denote the number of decimals the rounding or truncating must be applied to.
In the following example, we see the methods with and without arguments:
def bigDecimal = 42.576135
// Groovy uses BigDecimal for decimal
// numbers by default.
assert bigDecimal.class.name == 'java.math.BigDecimal'
assert bigDecimal.round() == 43
assert bigDecimal.round(2) == 42.58
assert bigDecimal.trunc() == 42
assert bigDecimal.trunc(2) == 42.57
Written with Groovy 2.5.0.
Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments