码迷,mamicode.com
首页 > Windows程序 > 详细

C# 扩展方法集

时间:2015-08-05 14:35:08      阅读:129      评论:0      收藏:0      [点我收藏+]

标签:

Humanizer(人性化)

Humanizer meets all your .NET needs for manipulating and displaying strings, enums, dates, times, timespans, numbers and quantities

 

string

// Return a string describing the value as a file size.
// For example, 1.23 MB.
public static string ToFileSize(this double value)
{
    string[] suffixes = { "bytes", "KB", "MB", "GB",
        "TB", "PB", "EB", "ZB", "YB"};
    for (int i = 0; i < suffixes.Length; i++)
    {
        if (value <= (Math.Pow(1024, i + 1)))
        {
            return ThreeNonZeroDigits(value /
                Math.Pow(1024, i)) +
                " " + suffixes[i];
        }
    }

    return ThreeNonZeroDigits(value /
        Math.Pow(1024, suffixes.Length - 1)) + 
        " " + suffixes[suffixes.Length - 1];
}
 
// Return the value formatted to include at most three
// non-zero digits and at most two digits after the
// decimal point. Examples:
//         1
//       123
//        12.3
//         1.23
//         0.12
private static string ThreeNonZeroDigits(double value)
{
    if (value >= 100)
    {
        // No digits after the decimal.
        return value.ToString("0,0");
    }
    else if (value >= 10)
    {
        // One digit after the decimal.
        return value.ToString("0.0");
    }
    else
    {
        // Two digits after the decimal.
        return value.ToString("0.00");
    }
}

C# 扩展方法集

标签:

原文地址:http://www.cnblogs.com/HQFZ/p/4635032.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!