-2

有人能帮我吗?我不确定是无知还是缺乏知识,但这真的很烦人。比较这种十进制格式123.456,22123,456.22.

我尝试这种方式:

十进制 val1 = 0; 十进制 val2 = 0;

decimal.TryParse("123,456.22", out val1);

decimal.TryParse("123.456,22", out val2);

如果计算机有123.456,22格式,我试试 decimal.TryParse( 123,456.22, out val1) --> val1 = 0;

现在我正在使用代码:按“,”或“。”分割 ,我只是想知道有什么更简单的方法可以做到这一点。

4

4 回答 4

1

使用 Decimal.Parse 方法:http: //msdn.microsoft.com/en-us/library/cafs243z.aspx

Decimal.Parse(value);

您可以使用重载方法传入文化(http://msdn.microsoft.com/en-us/library/t7xswkc6.aspx

Decimal.Parse(value, new CultureInfo("en-GB"));
于 2013-02-18T08:28:52.670 回答
0

试试这个:

decimal d1;
string s1 = "123,456.22";
if (Decimal.TryParse(s1, 
    System.Globalization.NumberStyles.Any, 
    System.Globalization.CultureInfo.GetCultureInfo("ro-RO"), 
    out d1))
{
    Console.WriteLine("Success: {0} converted into {1} using the ro-RO number format", 
        s1, d1);
}
else if (Decimal.TryParse(s1, out d1))
{
    Console.WriteLine("Success: {0} converted into {1} using the {2} number format", 
        s1, d1,System.Globalization.CultureInfo.CurrentCulture.Name);
}
    }
}

您可能会发现这篇 Wikipedia 文章很有趣:十进制标记

于 2013-02-18T08:39:29.400 回答
0

123.456,22并且123,456.22有一个不同的分隔符,而在一种情况下它的 point( .) 在另一种情况下它是一个逗号( ,),当你只使用 Parse 时它会依赖于当前的文化,所以其中一个会导致解析失败。

在这种情况下,您应该建立相关NumberFormatInfo并根据您对小数分隔符(NumberDecimalSeparator)和千位分隔符( NumberGroupSeparator)的需要进行设置

因此,您应该使用 TryParse,如果返回 false,则像这样构建您的自定义,并将其作为参数提供给 Parse。

// check with TryParse first and if it returns false then try as below
NumberFormatInfo numinf = new NumberFormatInfo();
numinf.NumberDecimalSeparator= ",";
numinf.NumberGroupSeparator= ".";
decimal.Parse("your failed tryparse", numinf);
于 2013-02-18T08:44:07.047 回答
0
decimal d1;
string s1 = "123,456.22";
if (Decimal.TryParse(s1, 
    System.Globalization.NumberStyles.Any, 
    System.Globalization.CultureInfo.GetCultureInfo("ro-RO"), 
    out d1))
{
    Console.WriteLine("Success: {0} converted into {1} using the ro-RO number format", 
        s1, d1);
}
else if (Decimal.TryParse(s1, out d1))
{
    Console.WriteLine("Success: {0} converted into {1} using the {2} number format", 
        s1, d1,System.Globalization.CultureInfo.CurrentCulture.Name);
}
    }
}

只能在控制台应用程序上使用??

于 2013-03-01T04:28:03.693 回答