1

How do I represent a long value in KB like the snapshot picture?

enter image description here

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Murhaf Sousli
  • 12,622
  • 20
  • 119
  • 185

2 Answers2

9

From my blog:

static string ReadableFileSize(double size, int unit=0)
{
    string[] units = { "B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };

    while(size >= 1024) {
        size /= 1024;
        ++unit;
    }

    return String.Format("{0:0.#} {1}", size, units[unit]);
}

Although this doesn't do specifically what you asked. If you have a long which represents the number of bytes, then all you have to do is divide by 1024. 1 KiB = 1024 B.


I also wrote a JavaScript version that's a bit more robust if anyone needs that.

mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • i need to do it like the format in the picture .. your method changes the value to MB when it becomes >= Math.Pow(1024, 2) .. – Murhaf Sousli Feb 27 '12 at 01:04
  • @MurHafSoz: Yes, which is why I wrote the second paragraph. Simply divide by 1024. Unless you were questioning how you format a number with commas.... but Yuriy explained that anyway. – mpen Feb 27 '12 at 05:57
5

This is probably what you're looking for:

long memory = 210957130;
Console.WriteLine("{0:N0} K", memory / 1024);
Console.WriteLine(string.Format(new CultureInfo("en-US"), "{0:N0} K", memory / 1024));

If you'd like to use the thousand separator from your current regional settings, use the first option. If you specifically want to use a comma, use the second option.

Yuriy Guts
  • 2,180
  • 1
  • 14
  • 18