# Convert string currency to double without knowing the format

2

I am trying to pass a string with random values with different currency formats:

``````1,222.50
1.222,50
1222.5
1222,500
1222
``````

To a double to be able to insert it in the database. So far I have the following code:

``````String a1, a2;
a1 = "1.100,50";
a2 = "1,100.50";
NumberFormat nf = NumberFormat.getInstance();
double number = nf.parse(a1).doubleValue();
double number2 = nf.parse(a2).doubleValue();
System.out.println(number);
System.out.println(number2);
``````

But this is the result I get:

``````1100.5
1.1
``````

It is not working for me in the English format. I tried the `Double.parseDouble(a1)` function but have problems with the Spanish format. Is there any way to pass it to Double regardless of the format it has?

asked by Genarito 31.01.2017 в 15:24
source

1

As mentioned, only a decimal point separator can exist, so you must identify it and replace it with a point so that the conversion to Double is correctly made.

I have never encountered the problem you represent, but I was curious and developed the following method quickly. You'll see that it always returns the decimal separator with the period and eliminates thousands separators.

``````public static String ajustaMoneda(String valor1)
{

int lastPosComas = -1;
int lastPosPuntos = -1;

lastPosComas = valor1.lastIndexOf(",");
lastPosPuntos = valor1.lastIndexOf(".");

if (lastPosComas > lastPosPuntos)
{
valor1 = valor1.replace(".", "");
valor1 = valor1.replace(",", ".");

}
else
{
valor1 = valor1.replace(",", "");
}

Double valorDouble = new Double(valor1);
System.out.println(valorDouble);

return valor1;
}
``````

With the examples that you put the result would be:

Value of 1,222.50: 1222.5

Value of 1,222.50: 1222.5

Value of 1222.5: 1222.5

Value of 1222,500: 1222.5

Value of 1222: 1222.0

I hope it suits your needs.

Greetings!