I am trying to parse string "0.0000" with double.TryParse()
but I have no idea why would it return false in this particular example. When I pass integer-like strings e.g. "5" it parses correctly to value of 5 .
Any ideas why it is happening ?
I am trying to parse string "0.0000" with double.TryParse()
but I have no idea why would it return false in this particular example. When I pass integer-like strings e.g. "5" it parses correctly to value of 5 .
Any ideas why it is happening ?
The most stupid thing about this is that it only accept "," as decimal separator in my culture, but the result is with a ".". Someone, somewhere, wasn't very lucky thinking that day... So I'll try this:
it takes the localization settings at runtime into account... perhaps you are running this on a system where
.
is not the decimal point but,
instead...In your specific case I assume you want a fixed culture regardless of the system you are running on with
.
as the decimal point:OR
Some MSDN reference links:
TryParse
uses the current culture by default. And if your current culture uses a decimal seperator different from.
, it can't parse0.0000
as you intend. So you need to pass inCultureInfo.InvariantCulture
.It will return
false
if the current culture specifies a decimal point separator that is different than the.
character.When parsing strings representation you need to be aware in what culture they are represented otherwise you'll get unexpected behavior.
In this case you're getting
false
, but it could even be worse, for example in the following example if you were expecting to get the number one you would instead get one thousand:This is because in the
pt-PT
culture the.
character is used asNumberGroupSeparator
and the,
character is used asNumberDecimalSeparator
.If the input you're parsing comes from the user then always parse it using the culture the user is associated. Getting the culture the user is associated is something dependent on the context, for example in a Windows Forms application you would use
Thread.CurrentThread.CurrentCulture
when on the UI thread to get it. In a ASP.NET application this may be different.From the MSDN page for this method.
http://msdn.microsoft.com/en-us/library/994c0zb1.aspx
Zero goes in, zero comes out.
Changing the CultureInfo with TryParse did nothing for me. I had to change the number formats under Control Panel (Change, date, time, or number formats) and changed the Decimal symbol. Than it worked again.