Parsing decimal with thousands separator

后端 未结 2 1429
醉梦人生
醉梦人生 2021-01-21 06:12

I have the following block of code:

string price = \"1,234.56\";
decimal value = 0;
var allowedStyles = (NumberStyles.AllowDecimalPoint & NumberStyles.AllowT         


        
相关标签:
2条回答
  • 2021-01-21 06:58

    The result of this binary and (&) will always be 0 (false, or NumberStyles.None). That's why it doesn't allow decimal and thousand separators:

    var allowedStyles = (NumberStyles.AllowDecimalPoint & NumberStyles.AllowThousands);
    

    Change to binary or (|):

    var allowedStyles = (NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands);
    
    0 讨论(0)
  • 2021-01-21 07:07

    If you AND-combine the NumberStyles-flag, you will get None.

    00100000 (AllowDecimalPoint)
    &
    01000000 (AllowThousands)
    --------
    00000000 (None)
    

    Try to OR-combine them: NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands

    00100000 (AllowDecimalPoint)
    |
    01000000 (AllowThousands)
    --------
    01100000 (AllowDecimalPoint, AllowThousands)
    

    Additionally, I'm afraid that you can't parse both styles (US style and DE style) with one statement.

    So I'd try both:

    string price = "1,234.56";
    decimal value = 0;
    var allowedStyles = (NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands);
    
    if (Decimal.TryParse(price, allowedStyles, CultureInfo.GetCultureInfo("DE-de"), out value))
    {
        Console.Write("Danke!");
    }
    else if (Decimal.TryParse(price, allowedStyles, CultureInfo.GetCultureInfo("EN-us"), out value))
    {
        Console.Write("Thank you!");
    }
    else
    {
        throw new InvalidFormatException();
    }
    
    0 讨论(0)
提交回复
热议问题