1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| public class Formatter { /** * get file format size * * @param context context * @param roundedBytes file size * @return file format size (like 2.12k) */ public static String formatFileSize(Context context, long roundedBytes) { return formatFileSize(context, roundedBytes, false, Locale.US); }
public static String formatFileSize(Context context, long roundedBytes, Locale locale) { return formatFileSize(context, roundedBytes, false, locale); }
private static String formatFileSize(Context context, long roundedBytes, boolean shorter, Locale locale) { if (context == null) { return ""; } float result = roundedBytes; String suffix = "B"; if (result > 900) { suffix = "KB"; result = result / 1024; } if (result > 900) { suffix = "MB"; result = result / 1024; } if (result > 900) { suffix = "GB"; result = result / 1024; } if (result > 900) { suffix = "TB"; result = result / 1024; } if (result > 900) { suffix = "PB"; result = result / 1024; } String value; if (result < 1) { value = String.format(locale, "%.2f", result); } else if (result < 10) { if (shorter) { value = String.format(locale, "%.1f", result); } else { value = String.format(locale, "%.2f", result); } } else if (result < 100) { if (shorter) { value = String.format(locale, "%.0f", result); } else { value = String.format(locale, "%.2f", result); } } else { value = String.format(locale, "%.0f", result); } return String.format("%s%s", value, suffix); }
}
|