Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 584
Mike U Avatar asked Jul 31 '12 01:07

Mike U


3 Answers

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));
like image 152
Daniel Avatar answered Oct 16 '22 05:10

Daniel


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

like image 44
Ramin Bateni Avatar answered Oct 16 '22 04:10

Ramin Bateni


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);
like image 4
dtb Avatar answered Oct 16 '22 05:10

dtb