format File Size, with or without keeping zero - Android java.io

Android examples for java.io:File Size

Description

format File Size, with or without keeping zero

Demo Code

import java.text.DecimalFormat;

public class Main {
  public static String formatFileSize(long len) {
    return formatFileSize(len, false);
  }//from w  w w  .  j ava2s.c  om

  public static String formatFileSize(long len, boolean keepZero) {
    String size;
    DecimalFormat formatKeepTwoZero = new DecimalFormat("#.00");
    DecimalFormat formatKeepOneZero = new DecimalFormat("#.0");
    if (len < 1024) {
      size = String.valueOf(len + "B");
    } else if (len < 10 * 1024) {
      size = String.valueOf(len * 100 / 1024 / (float) 100) + "KB";
    } else if (len < 100 * 1024) {
      size = String.valueOf(len * 10 / 1024 / (float) 10) + "KB";
    } else if (len < 1024 * 1024) {
      size = String.valueOf(len / 1024) + "KB";
    } else if (len < 10 * 1024 * 1024) {
      if (keepZero) {
        size = String.valueOf(formatKeepTwoZero.format(len * 100 / 1024 / 1024
            / (float) 100))
            + "MB";
      } else {
        size = String.valueOf(len * 100 / 1024 / 1024 / (float) 100) + "MB";
      }
    } else if (len < 100 * 1024 * 1024) {
      if (keepZero) {
        size = String.valueOf(formatKeepOneZero.format(len * 10 / 1024 / 1024
            / (float) 10))
            + "MB";
      } else {
        size = String.valueOf(len * 10 / 1024 / 1024 / (float) 10) + "MB";
      }
    } else if (len < 1024 * 1024 * 1024) {
      size = String.valueOf(len / 1024 / 1024) + "MB";
    } else {
      size = String.valueOf(len * 100 / 1024 / 1024 / 1024 / (float) 100)
          + "GB";
    }
    return size;
  }

}

Related Tutorials