首页  编辑  

字节数转成可读性强字符串的最简单有效的方法

Tags: /Android/   Date Created:
字节数,转换成人类可读性强的字符串的方法
Size byte to human readable string

Java版:

public static String humanReadableByteCount(long bytes, boolean si){
    int unit = si ? 1000 : 1024;
    if (bytes < unit) return bytes + " B";
    int exp = (int) (Math.log(bytes) / Math.log(unit));
    String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp-1) + (si ? "i" : "");
    return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
}

C# 版:

/// <summary>
/// 字节转换为科学计数法,最简单好用
/// </summary>
/// <param name="bytes">字节整数</param>
/// <param name="si">si为true表示科学计数法,即用1000做基数</param>
/// <returns></returns>
public static string SizeToReadable(Int64 bytes, bool si = false)
{
	int unit = si ? 1000 : 1024;
	if (bytes < unit) return bytes + " B";
	int exp = (int)(Math.Log(bytes) / Math.Log(unit));
	String pre = (si ? "kMGTPE" : "KMGTPE")[exp - 1] + (si ? "i" : "");
	return String.Format("{0:0.00} {1}B", bytes / Math.Pow(unit, exp), pre);
}