我有两个变量,一个是 double 型,一个是浮点型。我想通过一种方法设置度量单位,所以我写了这段代码。
double total = ((double)statFs.getAvailableBlocks() *statFs.getBlockSize());
double result = availableBlocks * blockSize;
myPreference.setSummary(setUnit(total, 0));
public String setUnit(double total, double size) {
String tutto = null;
String suffisso = null;
if (total >= 1024 || size >= 1024 ) {
suffisso = " KB";
total /= 1024;
size /= 1024;
tutto = total+size+suffisso;
}
if (total >= 1024 || size >= 1024 ) {
suffisso = " MB";
total /= 1024;
size /= 1024;
tutto = total+size+suffisso;
}
if (total >= 1024 || size >= 1024 ) {
suffisso = " GB";
total /= 1024;
size /= 1024;
tutto = total+size+suffisso;
}
return tutto;
}
您目前看到的方法仅适用于总浮时。我怎样才能使它在双变量大小的情况下也能工作?
编辑:现在它对两者都有效,但我看到了一个非常大的数字。示例:13.78565656898 如何取两个变量,只取小数点后第一位?
我设置方法的方式好不好?
最佳答案
将其更改为:
public String setUnit(double total)
它适用于 float 和 double。
注意:如果 setUnit() 的输入值小于 1024,setUnit() 将返回 null。为了防止它,只需再检查一次总计 < 1024,这将为您提供字节。要将返回的字符串格式化为小数点后 1 位,请使用 String.format(),因此您的 setUnit() 看起来像这样:
public static String setUnit(double total) {
String tutto = null;
String suffisso = null;
//if param passed to setnit() is < 1024 and > 0
//we don't have to to any calculations on total
//simply return it as it is with B (byte) as unit
if (total >= 0 && total < 1024) {
suffisso = " B";
tutto = String.format("%.1f", total) + suffisso;
}
if (total >= 1024) {
suffisso = " KB";
total /= 1024;
tutto = String.format("%.1f", total) + suffisso;
}
if (total >= 1024) {
suffisso = " MB";
total /= 1024;
tutto = String.format("%.1f", total) + suffisso;
}
if (total >= 1024) {
suffisso = " GB";
total /= 1024;
tutto = String.format("%.1f", total) + suffisso;
}
return tutto;
}
关于java - 设置单位度量的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20424482/