我有以下代码块:
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();
}
最终,price
将采用美式(即1,234.56)或德式(即1.234,56)。我的挑战是现在,Decimal.TryParse
失败了。我怀疑它是因为千位分隔符。这就是我添加allowedStyles
变量的原因。
我做错了什么?
答案 0 :(得分:5)
如果 AND - 组合NumberStyles
- 标记,您将获得None
。
00100000 (AllowDecimalPoint)
&
01000000 (AllowThousands)
--------
00000000 (None)
尝试或 - 组合它们:NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands
00100000 (AllowDecimalPoint)
|
01000000 (AllowThousands)
--------
01100000 (AllowDecimalPoint, AllowThousands)
此外,我担心您无法使用一个语句解析两种样式(美式和DE样式)。
所以我试试两个:
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();
}
答案 1 :(得分:1)
此二进制文件and
(&
)的结果将始终为0
(false
或NumberStyles.None
)。这就是为什么它不允许十进制和千位分隔符:
var allowedStyles = (NumberStyles.AllowDecimalPoint & NumberStyles.AllowThousands);
更改为二进制or
(|
):
var allowedStyles = (NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands);