简体   繁体   中英

How can I format a decimal without separators and without decimals?

How can I format a decimal to be converted to a string without group separators and without decimals?

For eg: "1,234.56" should be displayed as "1234".

This almost works, but rounds up:

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

Outputs: 1235

As @Jon Skeet suggested, you could cast to an integer type (assuming it was large enough to hold your largest decimal value):

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

Outputs: 1234

Demo: http://ideone.com/U4dcZD

I did not understand why you cant just use a cast. I think an Int will not show comma (,). But anyways, this should do the trick:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM