I am trying to load info from a properties file and i have the following code:
anInt = Integer.parseInt(prop.getProperty("anInt"));
aDouble = Double.parseDouble(prop.getProperty("aDouble"));
and while the first line works just fine, the second one where i am trying
to load a double variable throws a NumberFormatException
. The specific exception message is:
Exception in thread "main" java.lang.NumberFormatException: For input string: "78,5"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222)
at java.lang.Double.parseDouble(Double.java:510)
at Assignment1.BaseStation.readPropertyFile(BaseStation.java:59)
at Assignment1.BaseStation.main(BaseStation.java:83)
You have to use a period as a delimiter, not comma if you want to parse using Double.parseDouble()
. It says in documentation for the Double class that
FloatingPointLiteral ... [is] as defined in the lexical structure sections of the of the Java Language Specification.
From Java Language Specification:
FloatingPointLiteral:
- Digits . Digits opt ExponentPart opt FloatTypeSuffix opt
- . Digits ExponentPart opt FloatTypeSuffix opt
- Digits ExponentPart FloatTypeSuffix opt
- Digits ExponentPart opt FloatTypeSuffix
If you want to take locale into consideration, you can use java.text.NumberFormat
:
NumberFormat nf = NumberFormat.getInstance();
double number = nf.parse(myString).doubleValue();
If you want to use "," as some EU countries using. You have to carefully take care of your localization.
Look at java api http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html
at valueOf, it said
To interpret localized string representations of a floating-point value, use subclasses of NumberFormat.
For example, this code will solve your problem,
NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
double number = nf.parse(myString).doubleValue();
One important thing, you must not use something like
Locale.setDefault(something);
Because it can affect the whole JVM. In other words, that means it can affect the other codes which are using localization. Moreover it can affect the other apps which are in the same JVM if you are using Containner such as Servlet Container (such as shared Tomcat hosting).
And most of the time, something like Locale.setDefault() can be used in your local computer but you cannot deploy it on the other servers (shared tomcat hosting) because their JRE may be set permission to not allow to do such method. I'am pretty sure that most of good hosting providers did this. If you can deploy such this code on any shared Tomcats in any hosting providers, I strongly recommend you to change to another hosting company.
"." is usually used as comma separator. If you'd like to stick with "," you'll have to change the localisation settings:
Locale.setDefault(Locale.GERMAN); //German will do the trick, better to use your country code
or make use of the 'NumberFormat' class. It's explained really well int this stackover flow thread