Turi Messina
Turi Messina

Reputation: 1

Java: Double with comma from String with unknown decimal separator

Starting from a String variable I need to obtain a Double value of it with comma as decimal separator.

I can't know if String will contains int numbers or number with decimals separated by dot or comma, so I need to catch cases of unappropriate String values as presence of chars or multiple dots or commas.

Upvotes: 0

Views: 2889

Answers (2)

SMA
SMA

Reputation: 37023

Try something like:

String number = "20,981";
try {
    double dNumber = Double.parseDouble(number.replace(',', '.'));
    System.out.println("My double is " + dNumber);
} catch (NumberFormatException nfe) {
    System.out.println("I got exception for invalid string " + number);
}

Upvotes: 2

user1438038
user1438038

Reputation: 6059

You can either use parseString() or valueOf(). Surround your code with a try-catch-block to catch any NumberFormatExceptions. If you are unsure about whether your input String will contain a comma or a period, you may find the replace() useful (String class). Watch out, the first argument is a regular expression, so you need to escape the period!

Upvotes: 0

Related Questions