Ethyl Casin
Ethyl Casin

Reputation: 793

Unable to add BigDecimal value in Groovy

def total = new BigDecimal("0.00");
total.add(new BigDecimal("1"));
println total;

Consider the following code above: The output of this code is zero.

Why?

Upvotes: 1

Views: 1154

Answers (1)

cfrick
cfrick

Reputation: 37043

you have to assign the result (see the docs below). or get groovy:

def total = 0.0G + 1G
assert total.getClass() == BigDecimal
assert total==1.0G

total += 1.0G
assert total.getClass() == BigDecimal
assert total==2.0G

http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#add%28java.math.BigDecimal%29

 public BigDecimal add(BigDecimal augend)

Returns a BigDecimal whose value is (this + augend), and whose scale is max(this.scale(), augend.scale()).

Parameters:

augend - value to be added to this BigDecimal.

Returns:

this + augend

Upvotes: 2

Related Questions