Here you can find the source of formatBytes(long bytes)
Parameter | Description |
---|---|
bytes | Bytes to format. |
public static String formatBytes(long bytes)
//package com.java2s; import java.math.RoundingMode; import java.text.DecimalFormat; public class Main { /**/*from w w w . java 2s.c o m*/ * Format bytes to KB, MB or GB. * * @param bytes * Bytes to format. * @return Bytes formatted. */ public static String formatBytes(long bytes) { double size = 0; if (bytes < 1024) { return bytes + " Bytes"; } else if (bytes < 1048576) { size = bytes / 1024; return formatDecimal(size) + " KB"; } else if (bytes < 1073741824) { size = bytes / 1048576; return formatDecimal(size) + " MB"; } else { size = bytes / 1073741824; return formatDecimal(size) + " GB"; } } /** * Format decimal numbers to #.## * * @param size * Size to format. * @return Decimal formatted. */ public static String formatDecimal(double size) { DecimalFormat df = new DecimalFormat("#.###"); df.setRoundingMode(RoundingMode.CEILING); return df.format(size); } }