我需要在我的应用程序中接受 3 种十进制数据格式:
- 123456,78 => 123456.78
- 123,456.78 => 123456.78
- 123456.78 => 123456.78
我不能假设在特定情况下会使用一种格式。我需要的是从字符串中获取十进制值,无论它以哪种格式给出。
有没有聪明的方法来做到这一点?
我试图使用
var culture = CultureInfo.CreateSpecificCulture("en-US");
但这似乎不适用于 wp7。
到目前为止,我已经这样做了:
public static class Extensions
{
public static decimal toDecimal(this string s)
{
decimal res;
int comasCount=0;
int periodsCount=0;
foreach (var c in s)
{
if (c == ',')
comasCount++;
else if (c == '.')
periodsCount++;
}
if (periodsCount > 1)
throw new FormatException();
else if(periodsCount==0 && comasCount > 1)
throw new FormatException();
if(comasCount==1)
{
// pl-PL
//parse here
}else
{
//en-US
//parse here
}
return res;
}
}