Reputation: 1
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
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
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