Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Groovy Goodness: Truncate And Round BigDecimal Values

DZone's Guide to

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!

· Java Zone ·
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

Groovy 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.

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:
java ,groovy ,bigdecimal ,truncate ,round

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}