43

Is there a way using a string formatter to format Thousands, Millions, Billions to 123K, 123M, 123B without having to change code to divide value by Thousand, Million or Billion?

String.Format("{0:????}", LargeNumber)
Mike G
  • 4,232
  • 9
  • 40
  • 66
Mike U
  • 2,901
  • 10
  • 32
  • 44

3 Answers3

89

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));
MSeifert
  • 145,886
  • 38
  • 333
  • 352
Daniel
  • 1,195
  • 9
  • 13
29

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();

Ramin Bateni
  • 16,499
  • 9
  • 69
  • 98
4

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);
dtb
  • 213,145
  • 36
  • 401
  • 431