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

Automist automates your software deliver experience. It's how modern teams deliver modern software.

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.

Get the open source Atomist Software Delivery Machine and start automating your delivery right there on your own laptop, today!

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 }}