Substitute a hyphen for the dash:
var climateString = "−2.8".Replace ("−", "-");
var number = double.Parse(climateString);
(You might want to be on the lookout for other strange characters coming out of that database, though.)
質問
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!
解決 2
Substitute a hyphen for the dash:
var climateString = "−2.8".Replace ("−", "-");
var number = double.Parse(climateString);
(You might want to be on the lookout for other strange characters coming out of that database, though.)
他のヒント
Proper way to do it:
var climateString = "−2.8";
var fmt = new NumberFormatInfo();
fmt.NegativeSign = "−";
var number = double.Parse(climateString, fmt);
Might be an old post but for anyone else reading this...
You have NumberStyles.AllowTrailingSign, that should probably be NumberStyles.AllowLeadingSign otherwise it will not accept a - sign anyways.
I would suggest to use TryParse instead of Parse method because it gently handle you error if any.
Code -
var test1 = "-123.95";
decimal result;
decimal.TryParse(test1, out result);
you'll get parsed double value in result.
Try this:
decimal.TryParse(number, NumberStyles.AllowExponent | NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out decimal numberOut)