Best way to parseDouble with comma as decimal separator?
To convert a String
with a comma as a decimal separator into a double
, use DecimalFormat
with DecimalFormatSymbols
set to the appropriate Locale:
###,###.##", symbols); try { double number = format.parse(numberStr).doubleValue(); // Say "Au revoir" to the string! System.out.println(number); // Prints: 123.456, voila! } catch (Exception e) { e.printStackTrace(); // Sacré bleu! An error occured! } } }
**DecimalFormat** + **Locale-specific symbols** = a well-handled comma situation.
## Instant use of NumberFormat
When the task at hand involves quick parsing, a faster method is to simply use `NumberFormat`. Here’s how to put it to action:
```java
String numberStr = "123,456";
NumberFormat nf = NumberFormat.getInstance(Locale.FRANCE);
double number = nf.parse(numberStr).doubleValue(); //now number = 123.456, Magic!
Thanks to the NumberFormat
class, our parsing life is easier!
Quick and dirty approach
Now for those “I need a Double
now!” moments, a quick replace method is your friend:
It’s nifty and speedy but be cautious - it isn't locale-sensitive and may cause headaches!
When nothing else works, use regex
Regex might not be the most efficient, but it’s your life-saver on a rainy day. It can handle various numeric formats fluently:
Despite being slower than String.replace()
, this solution is a knight in shiny armour when the locale is unknown.
Juggling locales on the fly
When your code is expected to work with multiple languages, the flexible NumberFormat
can assist. Adapting to dynamic user locales becomes easy-peasy:
Break the language barrier
When you are dealing with varied locales in a multilingual application, NumberFormat
is your ally:
This ensures that the decimal parsing is compliant with the user's locale setting.
Magic with DecimalFormat and its Symbols
You can customize the numeric formatting for any complex requirements using DecimalFormat
and DecimalFormatSymbols
:
Was this article helpful?