Parsing double with comma as decimal separator

3.7k views Asked by At

I get inputs from user and read it line by line.Then I'm using split method to tokenize the inputs. Like this:

Scanner input=new Scanner(System.in);
String input1=input.nextLine();
String[] tokens=input1.split(" ");
method1(Double.parseDouble(tokens[0]),Double.parseDouble(tokens[1])); 

Here is method1:

 public static void method1 (double a, double b) {
    System.out.println(a);
    System.out.println(b);
 }

When I declare 3.5 and 5.3 output;

   3.5
   5.3

Here there is no problem but if I declare 3,5 and 5,3 my code giving error in below;

Exception in thread "main" java.lang.NumberFormatException: For input string: "3,5"
    at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
    at java.lang.Double.parseDouble(Unknown Source)

How can I fix this problem?

3

There are 3 answers

6
Maroun On

Using NumberFormat you can do something like this:

NumberFormat f = NumberFormat.getInstance(Locale.FRANCE);
double myNumber = f.parse("3,5").doubleValue();

Now you can pass myNumber to the method that accepts double value.

When using Locale.FRANCE, you tell Java that you write double numbers with , instead of ..

0
Salah On

You could use DecimalFormat like this:

DecimanFormat df = new DecimalFormat("#.#", DecimalFormatSymbols.getInstance());
Double returnValue = Double.valueOf(df.format(input1));

So DecimalFormatSymbols.getInstance() will get the default locale and its correct symbols.

Read More about DecimalFormat.

0
Mayur Gupta On

what i guess is : your input via scaner is

3.5 5.3

and you have applied

String[] tokens=input1.split(" ");

so it has divided your strings in to substrings ie 3.5 and 5.3 if you give your input as

3.5,5.3 

It will be a success and it will compile without an error..

in your case

input 3,5 5,3

it you just need to put a "," in split method like :

String[] tokens=input1.split(",");

and it will work with output as ....

3

5 5

3