Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# decimal.Parse behaviour

Short question:

Why are these '.....' valid for parsing a decimal in .NET (C#):

decimal res = decimal.Parse("8......15");  // returns 815
decimal res = decimal.Parse("8...15");     // returns 815
decimal res = decimal.Parse("8..15");      // returns 815

What's the reason for this?

like image 576
juFo Avatar asked Jan 13 '11 08:01

juFo


2 Answers

It fails for me. Are you by any chance in a culture where "." is the thousands separator and "," is the decimal point? Decimal.Parse (and similar calls) use the thread's current culture by default. Whether that is a good thing or not is debatable, but irrelevant to actual behaviour :)

Try specifying CultureInfo.InvariantCulture in the decimal.Parse call:

decimal res = decimal.Parse("8......15", CultureInfo.InvariantCulture);

I believe that will behave as you expected.

like image 174
Jon Skeet Avatar answered Sep 18 '22 16:09

Jon Skeet


I would imagine it's because the parser doesn't actually care about group separators - they are irrelevant to the process of converting a string to a decimal.

We call them thousands separators, but they're really not. They are group separators - you could split every 3 digits, every 10 digits, every 1 digit, so why not every 0 digits?

Interestingly, the code has changed for .NET 4 - this is the relevant output from Reflector for me:

else
{
    if (((currencySymbol == null) || 
         ((chPtr2 = MatchChars(p, currencySymbol)) == null)) && 
        ((ansiCurrencySymbol == null) || 
         ((chPtr2 = MatchChars(p, ansiCurrencySymbol)) == null)))
    {
        break;
    }
    num |= 0x20;
    currencySymbol = null;
    ansiCurrencySymbol = null;
    p = chPtr2 - 1;
}
like image 21
RB. Avatar answered Sep 22 '22 16:09

RB.