除了在解析在C#中的负双号 [英] Exception while parsing negative double numbers in C#
问题描述
我编码的code和平提取一些数据从数据库。而问题是,我想为负数串-2.8转换为双。 pretty的容易,我想。我想先用:
I'm coding a peace of code that extracts some data from a DB. And the problem is that I want to convert a negative number string "−2.8" to a double. Pretty easy, I thought. I tried first with:
var climateString = "−2.8";
var number = double.Parse(climateString);
通过这样的结果:
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
所以我想再次,搜索谷歌,并得到了新的答案:
So I thought again, searched on google, and got new answer:
var climateString = "−2.8";
var styles = NumberStyles.AllowParentheses | NumberStyles.AllowTrailingSign |NumberStyles.Float | NumberStyles.AllowDecimalPoint;
var rit = double.Parse(climateString, styles);
史诗再次失败:
Epic fail again:
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll
我想再说一次,我不能这么愚蠢不知道如何做这样一个简单的任务。我想这样的:
I thought again, I cannot be so stupid as not to know how to do such a simple task. I tried this:
var climateString = "−2.8";
var doue = Convert.ToDouble(climateString, CultureInfo.InvariantCulture);
是的,再次完全相同的例外。我开始寻找一个数目,而且,我实现了对负号。你看这个数字慎重-2.8这不是负数这一点。这是一个负数-2.8。再看看那些标志-----不一样。解析字符串用不同的符号字符抛出一个异常:S。因此,任何人有一个想法,如何优雅地分析它在C#中的双号? Thak你!
Yes, the exact same exception again. I started looking a the number, and, I realized on the negative sign. Look this number carefully "−2.8" this is not a negative number this. This is a negative number "-2.8". Look at those signs again "----- −−−−−" not the same. Parsing a string with a different sign character throws an exception : S. So, anyone has an idea, how to parse it elegantly to a double number in C#? Thak you!
推荐答案
正确的方式来做到这一点:
Proper way to do it:
var climateString = "−2.8";
var fmt = new NumberFormatInfo();
fmt.NegativeSign = "−";
var number = double.Parse(climateString, fmt);
这篇关于除了在解析在C#中的负双号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!