如何在没有分隔符和没有小数的情况下格式化小数?

时间:2013-03-07 04:03:24

标签: c#

如何格式化十进制数以转换为没有组分隔符且没有小数位的字符串?

例如:“1,234.56”应显示为“1234”。

2 个答案:

答案 0 :(得分:6)

这几乎可行,但总结了:

Decimal d = 1234.56M;
string s = string.Format("{0:0}", d);
Console.WriteLine(s);

输出:1235

正如@Jon Skeet建议的那样,你可以强制转换为整数类型(假设它足够大以保存最大的十进制值):

Decimal d = 1234.56M;
string s = string.Format("{0}", (long)d);
Console.WriteLine(s);

输出:1234

演示:http://ideone.com/U4dcZD

答案 1 :(得分:1)

我不明白为什么你不能使用演员。我认为Int不会显示逗号(,)。但无论如何,这应该可以解决问题:

        float n = 1234.78f;
        int i = (int)n;
        String str = i.ToString();
        while (str.IndexOf(",",0) >= 0 )
            str = str.Remove(str.IndexOf(",", 0), 1);