How do I represent a long value in KB like the snapshot picture?
Asked
Active
Viewed 4,624 times
2 Answers
9
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