Reputation: 53243
I am reading a value from my App.config; which is:
<add key="someValue" value="0.05"/>
And I try to convert it to double by doing:
var d = double.Parse(ConfigurationManager.AppSettings["someValue"]);
And I obtain 5.0 insteads of 0.05.
Can you advice? What do I do wrong and how should I parse this?
Upvotes: 6
Views: 3239
Reputation: 10118
Maybe the problem is in the culture settings. There could be many issues with them, such as comma as digital separator. When you're working with non-cultured values, such as config files, you should explicitly specify that you need InvariantCulture. Try
var d = double.Parse(ConfigurationManager.AppSettings["someValue"],
CultureInfo.InvariantCulture);
Upvotes: 8
Reputation: 3697
It's because of culture settings. Please ensure "." is a delimiter in your current culture.
Upvotes: -1
Reputation: 115741
This code:
var nfi = new NumberFormatInfo {
NumberGroupSeparator = ".",
NumberDecimalSeparator = ","
};
Console.WriteLine(double.Parse("0.05", nfi));
prints 5
as well, so the problem is in your culture settings.
Try
var d = double.Parse(
ConfigurationManager.AppSettings["someValue"],
CultureInfo.InvariantCulture);
Upvotes: 5
Reputation: 17964
Always pass your culture info when using double.Parse. Here in Belgium, it's "0,05".
Upvotes: 0
Reputation: 18237
That's for your culture settings, Test the same but with a comma instead a point and you will see that work's
var d = double.Parse("0,05");
To fixed this problem you could used the follow overload of the parse function
var d = double.Parse(ConfigurationManager.AppSettings["someValue"], CultureInfo.InvariantCulture);
Upvotes: 9