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 ?
TryParse(String, Double) Converts the string representation of a number to its double-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.
TryParse(String, Int32) Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.
TryParse(String, NumberStyles, IFormatProvider, Single) Converts the string representation of a number in a specified style and culture-specific format to its single-precision floating-point number equivalent. A return value indicates whether the conversion succeeded or failed.
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:
double.TryParse("0.0000", NumberStyles.Number, CultureInfo.CreateSpecificCulture ("en-US"), out temp)
OR
double.TryParse("0.0000", NumberStyles.Number,CultureInfo.InvariantCulture, out temp)
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 parse 0.0000
as you intend. So you need to pass in CultureInfo.InvariantCulture
.
var numberStyle = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | NumberStyles.AllowExponent;//Choose what you need double.TryParse( "0.0000", numberStyle, CultureInfo.InvariantCulture, out myVar)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With