栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

.NET是否提供一种简单的方式将字节转换为KB,MB,GB等?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

.NET是否提供一种简单的方式将字节转换为KB,MB,GB等?

这是一种相当简洁的方法:

static readonly string[] SizeSuffixes =         { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };static string SizeSuffix(Int64 value, int decimalPlaces = 1){    if (decimalPlaces < 0) { throw new ArgumentOutOfRangeException("decimalPlaces"); }    if (value < 0) { return "-" + SizeSuffix(-value); }     if (value == 0) { return string.Format("{0:n" + decimalPlaces + "} bytes", 0); }    // mag is 0 for bytes, 1 for KB, 2, for MB, etc.    int mag = (int)Math.Log(value, 1024);    // 1L << (mag * 10) == 2 ^ (10 * mag)     // [i.e. the number of bytes in the unit corresponding to mag]    decimal adjustedSize = (decimal)value / (1L << (mag * 10));    // make adjustment when the value is large enough that    // it would round up to 1000 or more    if (Math.Round(adjustedSize, decimalPlaces) >= 1000)    {        mag += 1;        adjustedSize /= 1024;    }    return string.Format("{0:n" + decimalPlaces + "} {1}",         adjustedSize,         SizeSuffixes[mag]);}

这是我建议的原始实现,可能会稍慢一些,但易于遵循:

static readonly string[] SizeSuffixes =        { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };static string SizeSuffix(Int64 value, int decimalPlaces = 1){    if (value < 0) { return "-" + SizeSuffix(-value); }    int i = 0;    decimal dValue = (decimal)value;    while (Math.Round(dValue, decimalPlaces) >= 1000)    {        dValue /= 1024;        i++;    }    return string.Format("{0:n" + decimalPlaces + "} {1}", dValue, SizeSuffixes[i]);}Console.WriteLine(SizeSuffix(100005000L));


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/568512.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号