Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why double.TryParse("0.0000", out doubleValue) returns false ?

Tags:

c#

parsing

double

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 ?

like image 396
Patryk Avatar asked Dec 11 '11 11:12

Patryk


People also ask

What is double TryParse?

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.

What is TryParse method?

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.

Can you TryParse a string?

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.


2 Answers

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:

  • Double.TryParse(String, NumberStyles, IFormatProvider, Double)
  • CultureInfo.CreateSpecificCulture(String)
  • IFormatProvider Interface
  • CultureInfo.InvariantCulture Property
like image 138
Yahia Avatar answered Oct 11 '22 11:10

Yahia


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) 
like image 27
CodesInChaos Avatar answered Oct 11 '22 10:10

CodesInChaos