Rounding off decimal value in Groovy

Posted by Anantha Narayanan On 9:56 PM 2 comments

I am new to groovy language, so assume its going to be bare basic.

By default you have an object defined in groovy like follows:

groovy> def number=12.11 
groovy> println number.round(2) 

Exception thrown

groovy.lang.MissingMethodException: No signature of method: java.math.BigDecimal.round() is applicable for argument types: (java.lang.Integer) values: [2]
Possible solutions: round(java.math.MathContext), find(), pow(int), and(java.lang.Number), power(java.lang.Integer), mod(java.lang.Number)

I was searching in google for identifying the issue, but could not resolve it. Later only I realized that round() is available in double in groovy. I then explicitly converted the variable to double using toDouble() method and chained the round() method to it. It solved my problem.

groovy> def number=12.11 
groovy> println number.getClass()
groovy> println number.toDoublt().getClass()
groovy> println number.toDouble().round(2) 

class java.lang.Double
class java.math.BigDecimal
12.11

So it is evident that the method round() is not available to BigDecimal whereas it is available to Double.

So how can I round off a BigDecimal? Waiting for the answer.

2 comments:

This is the same question I have. The problem in SoapUI is if you def a value through context.expand, i get an exception error.

I don't quite understand your question if you're trying to round with a decimaled number already. You trying to round to where you value is 12?

Hi,
You need to cast to float or to double before calling the round() method, which is not available on Integers or on BigDecimals:
((float) number).round()

Post a Comment

Recommended Post Slide Out For Blogger