正在尝试创建静态方法String formatSize(long sizeInBytes)
此方法需要针对提供的文件大小(以字节为单位)返回最合适的表示形式转换为人类可读的格式,至少应保留2个小数位(字节除外)。
这是我的代码
public class HexEditor {
public static void main(String[] args) {
System.out.println(formatSize(2147483647));
System.out.println(formatSize(123));
System.out.println(formatSize(83647));
System.out.println(formatSize(9585631));
System.out.println(formatSize(188900977659375L));
}
public static String floatForm (double d){
return new DecimalFormat("#.##").format(d);
}
public static String formatSize(long size) {
double B = 1 * 8;
double kibit = 1024;
double KiB = B * kibit;
double MiB = KiB * kibit;
double GiB = MiB * kibit;
double TiB = GiB * kibit;
double Pib = TiB * kibit;
if (size < kibit) {
return size + " byte";
} else if (size < KiB) {
double result = size / kibit;
return floatForm (result) + " Kibit";
} else if (size < MiB) {
double result = size / KiB;
return floatForm (result) + " KiB";
} else if (size < GiB) {
double result = size / MiB;
return floatForm (result) + " MiB";
} else if (size < TiB) {
double result = size / GiB;
return floatForm (result) + " GiB";
} else if (size < Pib) {
double result = size / TiB;
return floatForm (result) + " TiB";
}
return "";
}
}
这些是我的输入并期望输出
输入输出
2147483647 2.00 GiB
123 123 bytes
83647 81.69 KiB
9585631 9.14 MiB
188900977659375 171.80 TiB
但是当我的代码运行时,它给出了不同的输出
256 MiB
123 byte
10.21 KiB
1.14 MiB
21.48 TiB
我错了吗?或其他
您正在按位划分,但输入的字节数已已经。因此,除了 给下面的代码一个漩涡: double KiB = Math.pow(2, 10);
double MiB = Math.pow(2, 20);
double GiB = Math.pow(2, 30);
double TiB = Math.pow(2, 40);
double Pib = Math.pow(2, 50);
System.out.println("KiB: " + DecimalFormat.getInstance().format(KiB));
System.out.println("MiB: " + DecimalFormat.getInstance().format(MiB));
System.out.println("GiB: " + DecimalFormat.getInstance().format(GiB));
System.out.println("TiB: " + DecimalFormat.getInstance().format(TiB));
System.out.println("Pib: " + DecimalFormat.getInstance().format(Pib));
if (size < KiB) {
return size + " byte";
} else if (size < MiB) {
double result = size / KiB;
return floatForm(result) + " KiB";