Converting String using Float.parseFloat

I used WebUI.getText to fetch the amount value from the Web and used Float.parseFloat command to convert it from string to float so that I can create if else statement if the amount falls within certain value

However I encountered problem below:

  • Whenever the value is negative, the Float.parseFloat command would fail
  • Thus I had to create another if else statement before executing Float.parseFloat command: If -ve amount, split(’ ‘)[0], else split(’’)[0]

The above seems to work fine, until I encountered value exceeded 1000 as there is a comma separator for 000s.

Now I am kind of stuck as I tried different methods and couldn’t bypass this.

Search this forum for BigDecimal - try that instead of parseFloat.

Thanks for the suggestion.

I tried using the following commands:
rms_amt = WebUI.getText(findTestObject(‘Object Repository/div_RMspreadAmt’))
BigDecimal rms_amt_dec = BigDecimal (rms_amt)

But encountered error below:
groovy.lang.MissingMethodException: No signature of method: Script1559017349654.BigDecimal() is applicable for argument types: (java.lang.String) values: [1,325.62]

@belinda.tan

You have this:

BigDecimal rms_amt_dec = BigDecimal(rms_amt)

You should change it to:

BigDecimal rms_amt_dec = new BigDecimal(rms_amt)

See javadoc of BigDecimal : https://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html

@belinda.tan

You can parse a numeric string with comma, dot, sign etc into an instance of java.lang.Number value using java.text.DecimalFormat#parse(String) appropriately.
See for example
http://www.herongyang.com/JDK/Number-String-java-util-DecimalFormat-Parse-to-Object.html

You can cast a variable of java.lang.Number into a variable of type float by calling floatValue() method of Number. See https://www.tutorialspoint.com/java/lang/number_floatvalue.htm

1 Like

Thanks a lot @kazurayam. It works perfectly!