Is there a way to get Decimal.TryParse to parse a string value of
"0.0"or"00.00"or"000.000"as 0?
I am interpreting your question to mean. Say I take the strings "0.0", "00.00" and "000.000" ask Decimal.TryParse to parse them. When I write out the resulting decimal to the console I see 0.0, 0.00 and 0.000 respectively. Is there a way to get Decimal.TryParse to return a decimal in all these cases that will be written to the console as 0?
No. Think about why this should be. Decimal types represent precise numbers; in certain circles, 0.00 would be considered more precise than 0.0 which would be considered more precise than 0. If Decimal.TryParse truncated that precision than the Decimal type would not be useful for these purposes.
That said, it's easy enough to just trim the trailing zeros before calling parse:
static char[] whitespaceAndZero = new[] {
' ',
'\t',
'\r',
'\n',
'\u000b', // vertical tab
'\u000c', // form feed
'0'
};
static string TrimEndWhitespaceAndZeros(string s) {
return s.Contains('.') ? s.TrimEnd(whitespaceAndZero) : s;
}
static bool TryParseAfterTrim(string s, out decimal d) {
return Decimal.TryParse(TrimEndWhiteSpaceAndZeros(s), out d);
}
Usage:
string s = "0.00";
decimal d;
TryParseAfterTrim(s, out d);
Console.WriteLine(d);
Output:
0
Please note that the above only shows the crux of how to solve your problem. It is up to you to decide whether or not and how you are going to handle localization issues. At a minimum, before putting this into production you should consider replacing the hard-coded '.'
Why don't you use int.TryParse? or double.TryParse?
I see what you mean. The following code:
decimal number = -1.0M;
bool res1 = decimal.TryParse("0.0", out number);
Console.WriteLine(string.Format("number = {0}", number));
number = -1.0M;
bool res2 = decimal.TryParse("00.00", out number);
Console.WriteLine(string.Format("number = {0}", number));
number = -1.0M;
bool res3 = decimal.TryParse("000.000", out number);
Console.WriteLine(string.Format("number = {0}", number));
number = -1.0M;
bool res4 = decimal.TryParse("0000.0000", out number);
Console.WriteLine(string.Format("number = {0}", number));
prints:
number = 0.0
number = 0.00
number = 0.000
number = 0.0000
So the input does affect the output. But checking the value of number using the debugger shows "0" in the tooltip and Locals window which indicates that it's a formatting issue rather than a fundamental problem with the value being stored.
However, as others have said trim the trailing zeros (and decimal point) before converting.