如何使用Double.TryParse方法(String,NumberStyles,IFormatProvider,Double)

时间:2015-03-18 14:05:31

标签: c# .net

我正在尝试解析具有值“-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;

条件

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

始终返回false并且未设置经度。它只发生在前缀为“ - ”的字符串上。

4 个答案:

答案 0 :(得分:7)

您专门将NumberNegativeSign设置为“\ u2212”。这可能是官方的Unicode减号,但不是编程语言或数据通信中常用的。

当我使用普通的“ - ”(\ u002D,连字符 - 减号)时,你的示例解析。您的解析失败,因为输入中的负号不是您指定的。

答案 1 :(得分:3)

我通常使用以下内容:

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

忽略所有区域设置并使用大多数情况下使用的格式。

答案 2 :(得分:2)

这解决了我的问题

private new const NumberStyles Style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign;

显然,NumberStyles.Number搞砸了。

编辑: 发现我可以让它更简单

private new const NumberStyles Style = NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign;

var value = GetValue();
var unknownGeoCoordinate = GeoCoordinate.Unknown;

if (string.IsNullOrWhiteSpace(value))
    return unknownGeoCoordinate;

// The value of location in the Sitecore field is a pipe-separated string
// the first value is the latitude followed by pipe "|", then longitude
// Example: 67.2890989|14.401694
var latLng = value.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

if (latLng.Count() != 2)
    return unknownGeoCoordinate;

double latitude;
double longitude;

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

它可能也适用于

private new const NumberStyles Style = NumberStyles.Any;

感谢您的回答。

最佳, 比拉尔

答案 3 :(得分:0)

var numberFormatInfo = new NumberFormatInfo { NumberDecimalSeparator = ".", NegativeSign = "\u002d", NumberNegativePattern = 1 };

作品。

请参阅https://stackoverflow.com/a/2245138/12682

  

您可能希望使用真正的减号,Unicode代码点   \ u2212。你在编程中使用的减号(\ u002d)是一个   “hyphen-minus”,其归类顺序是上下文敏感的,因为它是   也经常用作连字符。这不仅仅是你想要的   了解this article中许多不同类型的短划线。