[英]Parsing decimal with thousands separator
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 (ie 1,234.56) or German style (ie 1.234,56). 最终, price
将采用美式(即1,234.56)或德式(即1.234,56)。 My challenge is right now, Decimal.TryParse
fails. 我现在面临的挑战是, Decimal.TryParse
失败了。 I suspect its because of the thousands separator. 我怀疑它是因为千位分隔符。 Which is why I added the allowedStyles
variable. 这就是我添加allowedStyles
变量的原因。
What am I doing wrong? 我究竟做错了什么?
If you AND -combine the NumberStyles
-flag, you will get None
. 如果你和 -combine的NumberStyles
-flag,你会得到None
。
00100000 (AllowDecimalPoint)
&
01000000 (AllowThousands)
--------
00000000 (None)
Try to OR -combine them: NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands
尝试对它们进行OR组合: NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands
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. 另外,我担心你不能用一个语句解析这两种样式(美式和DE样式)。
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();
}
The result of this binary and
( &
) will always be 0
( false
, or NumberStyles.None
). 此二进制文件and
( &
)的结果将始终为0
( false
或NumberStyles.None
)。 That's why it doesn't allow decimal and thousand separators: 这就是为什么它不允许十进制和千位分隔符:
var allowedStyles = (NumberStyles.AllowDecimalPoint & NumberStyles.AllowThousands);
Change to binary or
( |
): 更改为二进制or
( |
):
var allowedStyles = (NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.