Format Number like Stack Overflow (rounded to thousands with K suffix)

How to format numbers like SO with C#?

10, 500, 5k, 42k, ...


Solution 1:

Like this: (EDIT: Tested)

static string FormatNumber(int num) {
    if (num >= 100000)
        return FormatNumber(num / 1000) + "K";

    if (num >= 10000)
        return (num / 1000D).ToString("0.#") + "K";

    return num.ToString("#,0");
}

Examples:

  • 1 => 1
  • 23 => 23
  • 136 => 136
  • 6968 => 6,968
  • 23067 => 23.1K
  • 133031 => 133K

Note that this will give strange values for numbers >= 108.
For example, 12345678 becomes 12.3KK.

Solution 2:

The code below is tested up to int.MaxValue This is not the most beautiful code but is most efficient. But you can use it as:

123.KiloFormat(); 4332.KiloFormat(); 2332124.KiloFormat(); int.MaxValue.KiloFormat(); (int1 - int2 * int3).KiloFormat();

etc...

public static class Extensions
{
    public static string KiloFormat(this int num)
    {
        if (num >= 100000000)
            return (num / 1000000).ToString("#,0M");

        if (num >= 10000000)
            return (num / 1000000).ToString("0.#") + "M";

        if (num >= 100000)
            return (num / 1000).ToString("#,0K");

        if (num >= 10000)
            return (num / 1000).ToString("0.#") + "K";

        return num.ToString("#,0");
    } 
}

Solution 3:

You can crate a CustomFormater like this:

public class KiloFormatter: ICustomFormatter, IFormatProvider
{
    public object GetFormat(Type formatType)
    {
        return (formatType == typeof(ICustomFormatter)) ? this : null;
    }

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        if (format == null || !format.Trim().StartsWith("K")) {
            if (arg is IFormattable) {
                return ((IFormattable)arg).ToString(format, formatProvider);
            }
            return arg.ToString();
        }

        decimal value = Convert.ToDecimal(arg);

        //  Here's is where you format your number

        if (value > 1000) {
            return (value / 1000).ToString() + "k";
        }

        return value.ToString();
    }
}

And use it like this:

String.Format(new KiloFormatter(), "{0:K}", 15600);

edit: Renamed CurrencyFormatter to KiloFormatter

Solution 4:

A slightly modified version of SLaks code

static string FormatNumber(long num)
{
    if (num >= 100000000) {
        return (num / 1000000D).ToString("0.#M");
    }
    if (num >= 1000000) {
        return (num / 1000000D).ToString("0.##M");
    }
    if (num >= 100000) {
        return (num / 1000D).ToString("0.#k");
    }
    if (num >= 10000) {
        return (num / 1000D).ToString("0.##k");
    }

    return num.ToString("#,0");
}

This will return the following values:

 123        ->  123
 1234       ->  1,234
 12345      ->  12.35k
 123456     ->  123.4k
 1234567    ->  1.23M
 12345678   ->  12.35M
 123456789  ->  123.5M