Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How to format numbers like SO with C#?

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

like image 643
Yoann. B Avatar asked Jan 25 '10 17:01

Yoann. B


1 Answers

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.

like image 139
SLaks Avatar answered Sep 20 '22 12:09

SLaks