How do I convert from long value to KB string format

て烟熏妆下的殇ゞ 提交于 2020-01-05 12:34:33

问题


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.



来源:https://stackoverflow.com/questions/9458724/how-do-i-convert-from-long-value-to-kb-string-format

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!