String Format Numbers Thousands 123K, Millions 123M, Billions 123B

感情迁移 提交于 2019-11-27 03:34:27
Daniel

There are different ways to achieve this, but for me the easiest and quickest is to use the "," custom specifier

double value = 1234567890;

// Displays 1,234,567,890   
Console.WriteLine(value.ToString("#,#", CultureInfo.InvariantCulture));

// Displays 1,234,568K
Console.WriteLine(value.ToString("#,##0,K", CultureInfo.InvariantCulture));

// Displays 1,235M
Console.WriteLine(value.ToString("#,##0,,M", CultureInfo.InvariantCulture));

// Displays 1B
Console.WriteLine(value.ToString("#,##0,,,B", CultureInfo.InvariantCulture));

I use this mix of formats in an Extension Method (just add it to your project and enjoy) 😎

public static string ToKMB(this decimal num)
{
    if (num > 999999999 || num < -999999999 )
    {
        return num.ToString("0,,,.###B", CultureInfo.InvariantCulture);
    }
    else
    if (num > 999999 || num < -999999 )
    {
        return num.ToString("0,,.##M", CultureInfo.InvariantCulture);
    }
    else
    if (num > 999 || num < -999)
    {
        return num.ToString("0,.#K", CultureInfo.InvariantCulture);
    }
    else
    {
        return num.ToString(CultureInfo.InvariantCulture);
    }
}

Use:

((decimal)235).ToKMB();
// 235

((decimal)1235).ToKMB();
// 1.2K

((decimal)6271235).ToKMB();
// 6.27M

((decimal)93246571235).ToKMB();
// 93.247B

Notes:

  • It return more detail for bigger numbers and I like it.

  • It support negative numbers too. (Thanks to @Dusty for his note in comments.

  • I write a method for decimal numbers in this example, you can write some override methods for it to support int, long and double to use it without any casting such as:

    myIntNumber.ToKMB();

    myLongNumber.ToKMB();

    myDoubleNumber.ToKMB();

    myDecimalNumber.ToKMB();

You can implement a ICustomFormatter that divides the value by thousand, million or billion, and use it like this:

var result = string.Format(new MyCustomFormatter(), "{0:MyFormat}", number);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!