How can I have Decimal.TryParse parse 0.0?

.net, c#

Solution

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 `'.'` with `CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator`. You should consider having an overload of `TryParseAfterTrim` with the same parameter list as `Decimal.TryParse`. That is:

bool TryParseAfterTrim(
    string s,
    NumberStyle style,
    IFormatProvider provider,
    out decimal result
)

Problem

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 have tried setting NumberStyles to Any.

Original source