Damir
Damir

Reputation: 56179

String to Double in Java

I have in my Java app double numbers. I need to convert String to Double, but string representation of number is

, - separates decimal part of number ( example 1,5 eq 6/4 )

. - separates groups of three digits ( example 1.000.000 eq 1000000 )

. How to achieve this conversion String to Double ?

Upvotes: 4

Views: 516

Answers (5)

Mot
Mot

Reputation: 29520

DecimalFormat is your friend.

Upvotes: -1

aioobe
aioobe

Reputation: 420921

Here is one way of solving it using DecimalFormat without worrying about locales.

import java.text.*;

public class Test {

    public static void main(String[] args) throws ParseException {

        DecimalFormatSymbols dfs = new DecimalFormatSymbols();
        dfs.setGroupingSeparator('.');
        dfs.setDecimalSeparator(',');

        DecimalFormat df = new DecimalFormat();
        df.setGroupingSize(3);

        String[] tests = { "15,151.11", "-7,21.3", "8.8" };
        for (String test : tests)
            System.out.printf("\"%s\" -> %f%n", test, df.parseObject(test));
    }
}

Output:

"15,151.11" -> 15151.110000
"-7,21.3" -> -721.300000
"8.8" -> 8.800000

Upvotes: 5

danizmax
danizmax

Reputation: 2456

You need to get rid of the , and replace , with .:

String s = "1000.000,15";
double d = Double.valueOf(s.replaceAll("\\.", "").replaceAll("\\,", "."));   
System.out.print(d);

Upvotes: 1

OrangeDog
OrangeDog

Reputation: 38749

Looks like the German locale has that number format.

Double d = (Double) NumberFormat.getInstance(Locale.GERMAN).parse(s);

Upvotes: 3

jzd
jzd

Reputation: 23629

Use the parse method in DecimalFormat.

Upvotes: 1

Related Questions