c# - 在 C# 中解析负双数时出现异常

标签 c# .net c#-4.0 c#-3.0

我正在编写一段从数据库中提取一些数据的代码。问题是我想将负数字符串“−2.8”转换为 double 。很简单,我想。我先尝试了:

var climateString = "−2.8";
var number = double.Parse(climateString);

结果是:

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

于是我又想了想,google了一下,得到了新的答案:

var climateString = "−2.8";
var styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign |NumberStyles.Float | NumberStyles.AllowDecimalPoint;
var rit = double.Parse(climateString, styles);

史诗再次失败:

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

我又想了想,这么简单的事情我都不会傻到不知道怎么做的地步。我试过这个:

 var climateString = "−2.8";
 var doue = Convert.ToDouble(climateString, CultureInfo.InvariantCulture);

是的,又是完全相同的异常。我开始寻找数字,然后我意识到是负号。仔细看这个数字“-2.8”这不是负数这。这是一个负数“-2.8”。再看看那些标志“---------------------”不一样。解析具有不同符号字符的字符串会引发异常:S。那么,任何人都有想法,如何在 C# 中优雅地将其解析为 double ?谢谢你!

最佳答案

正确的做法:

var climateString = "−2.8"; 

var fmt = new NumberFormatInfo();
fmt.NegativeSign = "−";
var number = double.Parse(climateString, fmt);    

关于c# - 在 C# 中解析负双数时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22647548/

相关文章:

c# - StringBuilder 在 C# 内部是如何工作的?

.net - 没有生成 WPF .g.cs 文件?

c# - EnumerateFiles 中的配置 SearchPattern

c# - 是否有任何常用的 IQueryable 实现?

c# - 两个数组的并集

C# - Hook 到现有的 COM 对象

c# - 将字典从 <Parent, IEnumerable<Child>> 反转为 <Child, IEnumerable<Parent>>

c# - 在属性上触发事件/函数? (C#)

c# - "using"关键字是否意味着对象已被处置并被 GC 处理?

c#-4.0 - 使用动态关键字调用子类方法