Reputation: 393
I have two variables, one of type double and a float. I would like to set the unit of measure by a method so I wrote this code.
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;
}
he method that you see currently works only with the total float. How can I do to make it work even with the double variable size?
EDIT: Now it works for both, but I see a very large number. Example: 13.78565656898 how can I take for both variables, only the first decimal place?
The way I set the method is good or not?
Upvotes: 2
Views: 115
Reputation: 8598
Change it to:
public String setUnit(double total)
It will work both with float and double.
NOTE: If your input value for setUnit() is < 1024, setUnit() will return null. To prevent it, just add one more check for total < 1024, which will give you bytes. And to format the returned string to 1 decimal places, use String.format(), so your setUnit() would look something like this:
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;
}
Upvotes: 1
Reputation: 287
Another possiblity is to write two functions to support both float and double as follows, where one function calls the other. I'm not a fan of letting the compiler implicidly cast float to double or vise-versa as suggested in previous posts in order for one function to support both float and double in the same argument. Also, 'getTotalWithUnit' is clearer on what you are trying to accomplish than 'getUnit' which implies only the unit is returned, without a value.
public String getTotalWithUnit(float total) {
Float item = Float.valueOf(total);
return getTotalWithUnit( item.doubleValue());
}
public String getTotalWithUnit(double total) {
//do business logic here and return result rather than null
return null;
}
Upvotes: 0