String Format Numbers Thousands 123K, Millions 123M, Billions 123B
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 supportint
,long
anddouble
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);