How to convert currency string "$23.99" to number or float 23.99

I get text from an Element which is “$23.99”. Now I want to perform some operation or verification on this text like number comparison or addition etc. How should i convert this to number / float i.e. 23.99.

Couldn’t you use ‘getText’, save that in an object that gets text containing the numbers ‘23.99’ and then save that object in a variable? Then refer to that variable when performing the comparison later?

Find text on page e.g. //*[contains(text(), ‘23.99’]

save that in an object e.g. priceObj

save to an output e.g. String price = WebUI.callTestCase(findTestCase(priceObj))

Refer to the price variable later on when making the addition or comparison

Perhaps, try one of the methods on the below page:

https://www.java67.com/2015/06/how-to-convert-string-to-double-java-example.html#:~:text=There%20are%20three%20ways%20to,double%20primitive%20in%20no%20time.

Give us a report back if it works.

Another alternative is to use the String method, replace(). An example would be
someValue = someValue.replace("$", “”);

Maybe after replacing the dollar sign, you can use the conversion of String to Double such as in the first link.

1 Like

I used below approach:

  1. I created a custom keyword with below code:
    @Keyword
    public static BigDecimal parseCurrencyToFloat(final String amt, final Locale locale) throws Exception {
    final NumberFormat format = NumberFormat.getNumberInstance(locale);
    if (format instanceof DecimalFormat) {
    ((DecimalFormat) format).setParseBigDecimal(true);
    }
    return (BigDecimal) format.parse(amt.replaceAll("[^\d.,]",""));
    }

  2. Called this keyword with below statements:
    BigDecimal creditsNumber = CustomKeywords.‘general.Conversions.parseCurrencyToFloat’(creditsAvailable, Locale.US)
    //Pass the different currency values here Like Locale.US, Locale.FRANCE

println(creditsNumber)
// Printing this shows only numbers and i can perform operations on it.

This resolved my purpose of getting text and performing number operations.

Let me know if this is an efficient solution of using BigDecimal.

println(Double.parseDouble(WebUI.getText(findTestObject

can change Double to other types

and also can store as var

String myVar = println(Double.parseDouble(WebUI.getText(findTestObject