Reputation: 5323
I am trying to move the following string "-5017.85" into a decimal variable
I've tried
var sAmount = float.Parse(line[1]);
sAmount = decimal.Parse(line[1]);
sAmount = double.Parse(line[1]);
sAmount = decimal.Parse(line[1], NumberStyles.Currency);
sAmount = decimal.Parse(line[1], NumberStyles.AllowLeadingSign);
but none work. I get a system.formatexception
what am I missing?
EDIT: I had debugged of course and the value is actually: "\"-5017.85\""
and I assumed the \
were escape characters but when I removed them from the variable in watch window then the parsing works just fine. After removing 'escape characters' "-5017.85"
EDIT 2: this works and give me the correct answer but I do not like it at all
line[1].Remove(line[1].Length-1,1).Remove(0,1)
any better ways of doing this?
Upvotes: 0
Views: 440
Reputation: 241651
Something is clearly not right here, I suspect that line[1]
is not what you think it is. Are you sure that line[1] == "-5017.85"
is true
?
Another possible scenario that you have a different culture setting that is preventing -
from being parsed as the optional sign character or .
as the decimal-point separator, but this is an unlikely scenarios.
If you're sure that line[1] == "-5017.85"
is true
, could you please try
var sAmount = Decimal.Parse(
line[1],
System.Globalization.CultureInfo.InvariantCulture
);
and report back.
I had debugged of course and the value is actually:
"\"-5017.85\""
Well, in that case, I'd merely use String.Replace
to replace the \"
characters with the empty string as in:
var sAmount = Decimal.Parse(line[1].Replace("\"", ""));
Upvotes: 3
Reputation: 1690
So looks like your string contains an unnecessary " character. You can remove it like so, using string.replace:
sAmount = decimal.Parse(line[1].Replace("\"", ""));
Upvotes: 1
Reputation: 13523
Try double.Parse(line[1].Trim());
; it seems there are non-numeric, white space characters there.
Upvotes: 0