Friday, August 6, 2010

Format MemorySize to Readble Value (bytes to KB /MB/GB)

AIM: to Format the Memory Size  
Input:20109bytes
Output:20kb
Solution:
Step 1) Write a method to convert the sizes.
public String formatSize(long size) {
String suffix = null;

if (size >= 1024) {
suffix = "KiB";
size /= 1024;
if (size >= 1024) {
suffix = "MiB";
size /= 1024;
}
}
StringBuilder resultBuffer = new StringBuilder(Long.toString(size));

int commaOffset = resultBuffer.length() - 3;
while (commaOffset > 0) {
resultBuffer.insert(commaOffset, ',');
commaOffset -= 3;
}

if (suffix != null)
resultBuffer.append(suffix);
return resultBuffer.toString();
}
Step 2) Call this method as
String formattedMemory= formatSize(100000);
Result : 
formattedMemory will have in 10MB.




1 comment:

  1. how would you add the KB if the size is say 1.5 MB? Your code does not take that into account.

    thx

    ReplyDelete

Android Developers Blog

Ram's shared items

Amazon Product Ads