Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Double.TryParse Method (String, NumberStyles, IFormatProvider, Double)

Tags:

c#

.net

I'm trying to try parse a longitude that has the value "-51.739253997802734".

var unknownGeoCoordinate = GeoCoordinate.Unknown;
double latitude;
double longitude;
var numberFormatInfo = new NumberFormatInfo { NumberDecimalSeparator = ".", NegativeSign = "\u2212", NumberNegativePattern = 1 };
const NumberStyles style = NumberStyles.AllowLeadingSign | NumberStyles.Number | NumberStyles.AllowDecimalPoint;

if (!double.TryParse(latLng.First(), style, numberFormatInfo, out latitude) || !double.TryParse(latLng.Last(), style, numberFormatInfo, out longitude))
    return unknownGeoCoordinate;

The condition

double.TryParse(latLng.Last(), style, numberFormatInfo, out longitude)

always returns false and longitude is not set. It only happens for strings prefixed with "-".

like image 591
Bilal Isa Avatar asked May 19 '26 11:05

Bilal Isa


2 Answers

You are specifically setting the NumberNegativeSign to "\u2212". This may be the official Unicode Minus Sign, but is not what is usually used in programming languages or data communication.

Your example does parse when I use a plain "-" (\u002D, Hyphen-minus). Your parsing failed because the negative sign in the input was not what you specified.

like image 140
Hans Kesting Avatar answered May 20 '26 23:05

Hans Kesting


I usually use the following:

double d;
double.TryParse("-3.1415", NumberStyles.Any, NumberFormatInfo.InvariantInfo, out d);

Which ignores all regional settings and uses the format which is used in most cases.

like image 45
helb Avatar answered May 20 '26 23:05

helb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!