kd_testing
kd_testing

Reputation: 3

Reading string from webelement and it's conversion to decimals

One scenario is there in which i am reading the currencies from the webelement, and it's a string. Needed to convert it in number format for some P&L Calculation.

Tried below code

public class NumberFormat {

    public static void main(String[] args) {
        //String str = "$9.9967";
        String str1 = "€12,32123";
        String str2 = "€3.452,35";
        str1 = str1.replace(",", ".").replace(".", "").replaceAll("[^0-9.]", "");
        str2 = str2.replace(",", ".").replace(".", "").replaceAll("[^0-9.]", "");
        double str1Ch = Double.parseDouble(str1);
        double str2Ch = Double.parseDouble(str2);
        System.out.println(str1Ch);
        System.out.println(str2Ch);
    }

}

Actual Result:

1232123.0
345235.0

Expected Result:

12.32123
3452.35

I am not getting what I am expecting, I need to perform both conversion simultaneous( dot to null/empty, comma to dot)

Need to know why code is not working and also any suggestions for reading different country currencies and converting it into number format.

Upvotes: 0

Views: 391

Answers (3)

Pshemo
Pshemo

Reputation: 124225

One of options could be creating your own NumberFormat (here based on DecimalFormat). You can use DecimalFormatSymbols to set its decimal separator or grouping separator symbols.

Demo:

DecimalFormat df = new DecimalFormat("€#,###.#");
DecimalFormatSymbols dfSymbols = new DecimalFormatSymbols();
dfSymbols.setDecimalSeparator(',');
dfSymbols.setGroupingSeparator('.');
df.setDecimalFormatSymbols(dfSymbols);

String str1 = "€12,32123";
String str2 = "€3.452,35";
double str1Ch = df.parse(str1).doubleValue();
double str2Ch = df.parse(str2).doubleValue();

System.out.println(str1Ch);//12.32123
System.out.println(str2Ch);//3452.35

Upvotes: 2

jeanr
jeanr

Reputation: 1059

You can do this using NumberFormat

String s1 = "€3.452,35";

Locale locale = null;
switch (s1.charAt(0)) {
    case '€':
        locale = Locale.FRANCE;
        break;
    case '$':
        locale = Locale.US;
        break;
    //Add any other money you want
    default:
        //Money unexpected
}

s1 = s1.substring(1, s1.length())
        .replaceAll("[. ]", "")
        .replaceAll(",", ".");
System.out.println(s1);
NumberFormat nf = NumberFormat.getCurrencyInstance(locale);
System.out.println(nf.format(new BigDecimal(s1)));

Upvotes: 1

Rinor
Rinor

Reputation: 1979

You mixed up the replacement of the symbols comma and period.

i.e. first replace the periods with empty strings, then replace the comma with periods. As shown below.

    str1 = str1.replace(".", "").replace(",", ".").replaceAll("[^0-9.]", "");
    str2 = str2.replace(".", "").replace(",", ".").replaceAll("[^0-9.]", "");

Upvotes: 1

Related Questions