Double + Double = Too Many Decimals

I have two fields, Lodging Base and Lodging Tax. Their Object’s Property “type” equals text, even though the user is only allowed to enter numeric values. After either field loses focus, a dollar sign with a space before the numbers is added to the field.

I set the values in those using

WebUI.setText(findTestObject(‘LodgingBaseRate’), ‘89.01’)
WebUI.setText(findTestObject(‘LodgingTax’), ‘27.32’)

To add those values together, I’m using

lodgingBase = WebUI.getAttribute(findTestObject(‘LodgingBaseRate’),‘value’).replace(’$’, ‘’) as Double
lodgingTaxes = WebUI.getAttribute(findTestObject(‘LodgingTax’),‘value’).replace(’$’, ‘’) as Double
lodgingTotal = lodgingBase + lodgingTaxes

When I set the text of a field to lodgingTotal using

WebUI.setText(findTestObject(‘OtherExpenses’), ‘lodging: $’ + lodgingTotal)

…the result in the field is lodging: $116.33000000000001.

In my newbie attempts to fix all of those extra decimal places, I’ve tried the below two shots at it, but to no avail to get the answer to also be two decimal places. Any suggestions?

lodgingTotal = lodgingBase + lodgingTaxes as Double

lodgingTotal = (lodgingBase + lodgingTaxes) as Double

This is the standard behavior of the Double class in Java.

BigDecimal is a better choice.

As part of the BigDecimal class, Groovy offers a round method that accept a precision integer value.

def x = 89.01 as Double
def y = 27.32 as Double

print 'Sum of x + y = ' + (x + y).round(2)

This outputs 116.33 BigDecimal value instead of 116.33000000000001

Remove the round method and the result will be a Double value.

Should learn BigDecimal. For example, see

1 Like

Thanks so much for the info and opening my eyes to the BigDouble class!

1 Like

@jason.tolotta Following up on this, I changed my line to

lodgingTotal = (lodgingBase + lodgingTaxes).round(2)

…and that worked perfectly. But, it just so happened that after I implemented that fix, I updated my Java SDK to 12.0.2. After the update, the above code change didn’t work, with the reason shown as:

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), find(groovy.lang.Closure), mod(java.lang.Number), and(java.lang.Number)

I went through the suggested link provided by @kazurayam, resulting in changing the code line to

lodgingTotal = (lodgingBase + lodgingTaxes).setScale(2, BigDecimal.ROUND_HALF_UP)

…which works perfectly.

1 Like

@hhomberg katalon does not suport java greater than 8. aka 1.8.xx. at all. so … why would you want to try java 12 with it?
doing that you are on your own,nobody will take a look into an unsuported code …

1 Like

Aha. Good to know that, too!

1 Like