java根据字节数B转成合适的单位,工具类

Posted 爱米酱

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java根据字节数B转成合适的单位,工具类相关的知识,希望对你有一定的参考价值。


public class beautifySizeUtil 
public static String beautifySize(double size)
if (size <= 0) return "0";
final String[] units = new String[]"B", "KB", "MB", "GB", "TB";
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + "" + units[digitGroups];


public static String beautifySize(long size)
if (size <= 0) return "0";
final String[] units = new String[]"B", "KB", "MB", "GB", "TB";
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + "" + units[digitGroups];


//返回该B对应的美化单位
public static String beautifyUnit(long size)
if (size <= 0) return "B";
final String[] units = new String[]"B", "KB", "MB", "GB", "TB";
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return units[digitGroups];



//B转KB
public static String beautifyKb(long size)
DecimalFormat df = new DecimalFormat("#.00");
String beauSize = "";
beauSize = df.format((double) size / 1024);
return beauSize;

//B转MB
public static String beautifyMb(long size)
DecimalFormat df = new DecimalFormat("#.00");
String beauSize = "";
beauSize = df.format((double) size / 1048576);
return beauSize;

//B转GB
public static String beautifyGb(long size)
DecimalFormat df = new DecimalFormat("#.00");
String beauSize = "";
beauSize = df.format((double) size / 1073741824);
return beauSize;

//B转TB
public static String beautifyTb(long size)
DecimalFormat df = new DecimalFormat("#.00");
String beauSize = "";
beauSize = df.format((double) size / 1099511627776L);
return beauSize;


public static void main(String[] args)
System.out.println(beautifySize(1));
System.out.println(beautifySize(2048));
System.out.println(beautifySize(200000));
System.out.println(beautifySize(200000000));
System.out.println(beautifySize(2000000000));

执行结果:

java根据字节数B转成合适的单位,工具类_开发语言

以上是关于java根据字节数B转成合适的单位,工具类的主要内容,如果未能解决你的问题,请参考以下文章

powershell 根据文件中的字节数转换文件大小单位

计算机中用的各种单位之间是怎么转换的

在页面js 中,怎么将中文字符串转换成2个字节长度16进制数;并在js 环境下解码16进

信息单位

计算机存储单位和网络网速单位

Delphi Integer 转成单字节