Parsing decimal with thousands separator

本秂侑毒 提交于 2019-12-12 15:30:32

问题


I have the following block of code:

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

if (Decimal.TryParse(price, allowedStyles, CultureInfo.InvariantCulture, out value))
{
    Console.log("Thank you!");
}
else
{
    throw new InvalidFormatException();
}

Ultimately, price will either be in US style (i.e. 1,234.56) or German style (i.e. 1.234,56). My challenge is right now, Decimal.TryParse fails. I suspect its because of the thousands separator. Which is why I added the allowedStyles variable.

What am I doing wrong?


回答1:


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();
}



回答2:


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);


来源:https://stackoverflow.com/questions/29147178/parsing-decimal-with-thousands-separator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!