Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception while parsing negative double numbers in C#

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);

With this result:

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);

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!

like image 404
Fritjof Berggren Avatar asked Mar 25 '14 22:03

Fritjof Berggren


People also ask

Can we store negative value in double?

Floating-Point Data Example On all machines, variables of the float, double, and long double data types can store positive or negative numbers.

Can C++ doubles be negative?

Floating-Point Types float and double These are numbers that can be positive or negative.

Can you have negative doubles in Java?

One of the tricky parts of this question is that Java has multiple data types to support numbers like byte, short, char, int, long, float, and double, out of those all are signed except char, which can not represent negative numbers.


1 Answers

Proper way to do it:

var climateString = "−2.8"; 

var fmt = new NumberFormatInfo();
fmt.NegativeSign = "−";
var number = double.Parse(climateString, fmt);    
like image 189
Søren Debois Avatar answered Sep 28 '22 02:09

Søren Debois