I know this is an old question but I can't help but notice most of these answers are not far expandable, most of them are very similar lines of code repeated for more values. I needed something that worked on bigger values so instead of repetetive code I tried using math in a smart way. This does require using floating point math (doubles) as the maximum value of an unsigned long is only 1.84e+19. My solution:
public static string GetStringRepresentation(double count)
{
string tokens = " KMBtqQsSondUDT"; //Infinitely expandable (at least to the limit of double floating point values)
for (double i = 1; true; i += 1)
{
double val = Math.Pow(1000, i);
if (val > count)
{
return $"{count / Math.Pow(1000, i - 1)}{tokens[(int)i - 1]}".Trim();
}
}
}
Test code:
Console.WriteLine(" 1: " + GetStringRepresentation( 1).PadLeft(7, ' '));
Console.WriteLine(" 12: " + GetStringRepresentation( 12).PadLeft(7, ' '));
Console.WriteLine(" 123: " + GetStringRepresentation( 123).PadLeft(7, ' '));
Console.WriteLine(" 1230: " + GetStringRepresentation( 1230).PadLeft(7, ' '));
Console.WriteLine(" 12340: " + GetStringRepresentation( 12340).PadLeft(7, ' '));
Console.WriteLine(" 123450: " + GetStringRepresentation( 123450).PadLeft(7, ' '));
Console.WriteLine(" 1230000: " + GetStringRepresentation( 1230000).PadLeft(7, ' '));
Console.WriteLine(" 12340000: " + GetStringRepresentation( 12340000).PadLeft(7, ' '));
Console.WriteLine(" 123450000: " + GetStringRepresentation( 123450000).PadLeft(7, ' '));
Console.WriteLine(" 1230000000: " + GetStringRepresentation( 1230000000).PadLeft(7, ' '));
Console.WriteLine(" 1230000000000: " + GetStringRepresentation( 1230000000000).PadLeft(7, ' '));
Console.WriteLine(" 1230000000000000: " + GetStringRepresentation( 1230000000000000).PadLeft(7, ' '));
Console.WriteLine(" 1230000000000000000: " + GetStringRepresentation(1230000000000000000).PadLeft(7, ' '));
Output:
1: 1
12: 12
123: 123
1230: 1,23K
12340: 12,34K
123450: 123,45K
1230000: 1,23M
12340000: 12,34M
123450000: 123,45M
1230000000: 1,23B
1230000000000: 1,23t
1230000000000000: 1,23q
1230000000000000000: 1,23Q