rlong98
Contributor
10 years ago
Solved

# How to round a decimal value when working with context.expand number values?

I'm to verify values of an equation that is happening on the back end.

Example Values:
wages = 29250
divby = 11670
Should Equal = 2.5064267352 //which it does

QUESTION:  I need the result value I"m asserting is to = 2.51

def testValuea = context.expand( '\${Properties#a}' ) as int //--11670
def testValueb = context.expand( '\${Properties#b}' ) as int //--29250

result = (testValueb / testValuea)*100

//now my value is 250.64267352

QUESTION:  How do I get this to round to (3)?
Not sure where to use .Round(3) or if to use something else.

Thank you,
Rob

• Thanks Rupert

I did find this:

(<math equation>).toDouble().round(3)

Still a rookie in the scripting work - not understanding the "Double" term.

Thanks again...

Rob

### 3 Replies

• rupert_anderson
Valued Contributor

Hi,

Think this is more of a Groovy question than a SoapUI question, but assuming your value can be represented as a double then you can do something like:

For 2 decimal places:

def result=2.5064267352

log.info new Double(result).round(2) //2.51
assert new Double(result).round(2)==2.51  //OK

For 3 decimal places:

log.info new Double(result).round(3) //2.506
assert new Double(result).round(3)==2.506  //OK

If by 'to (3)' you mean 2.506... rounded to 3, then new Double(result).round(0) will give you 3.0, new Double(result).round() will give you 3

Hope this helps,

Cheers,

Rupert

• Thanks Rupert

I did find this:

(<math equation>).toDouble().round(3)

Still a rookie in the scripting work - not understanding the "Double" term.

Thanks again...

Rob

• rupert_anderson
Valued Contributor

Hi Rob,

No problem, happy to help :-)

In terms of the need for casting to Double, the reason I did that is because when you do:

def result=2.5064267352

This stores result as a BigDecimal by default. The cast to Double provides that class's round method.

Now BigDecimals can be rounded, but not using that simple 'round' method, which I thought you'd prefer, as its easier to get used to.

Hope that helps,

Cheers,

Rupert