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 though
You have a character that is not the minus character used in numbers (you have hyphen, not dash). You have to replace it, there's no other "elegant" way. Those two characters only visually resemble each other but they are not meant to replace each other without a change of meaning.
var climateString = "−2.8";
var number = double.Parse(climateString.Replace("−","-"));
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.)
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.
Proper way to do it:
var climateString = "−2.8";
var fmt = new NumberFormatInfo();
fmt.NegativeSign = "−";
var number = double.Parse(climateString, fmt);