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!
Floating-Point Data Example On all machines, variables of the float, double, and long double data types can store positive or negative numbers.
Floating-Point Types float and double These are numbers that can be positive or negative.
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.
Proper way to do it:
var climateString = "−2.8";
var fmt = new NumberFormatInfo();
fmt.NegativeSign = "−";
var number = double.Parse(climateString, fmt);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With