How do I convert from long value to KB string form

2019-08-12 13:29发布

问题:

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

回答1:

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.



回答2:

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.



标签: c# string format