Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I asked the same Question recently:</p> <p><a href="https://stackoverflow.com/questions/3263892/format-file-size-as-mb-gb-etc">Format file size as MB, GB etc</a></p> <p>While there is no out-of-the-box answer, I can live with the solution:</p> <pre><code>private static final long K = 1024; private static final long M = K * K; private static final long G = M * K; private static final long T = G * K; public static String convertToStringRepresentation(final long value){ final long[] dividers = new long[] { T, G, M, K, 1 }; final String[] units = new String[] { "TB", "GB", "MB", "KB", "B" }; if(value &lt; 1) throw new IllegalArgumentException("Invalid file size: " + value); String result = null; for(int i = 0; i &lt; dividers.length; i++){ final long divider = dividers[i]; if(value &gt;= divider){ result = format(value, divider, units[i]); break; } } return result; } private static String format(final long value, final long divider, final String unit){ final double result = divider &gt; 1 ? (double) value / (double) divider : (double) value; return new DecimalFormat("#,##0.#").format(result) + " " + unit; } </code></pre> <p>Test code:</p> <pre><code>public static void main(final String[] args){ final long[] l = new long[] { 1l, 4343l, 43434334l, 3563543743l }; for(final long ll : l){ System.out.println(convertToStringRepresentation(ll)); } } </code></pre> <p>Output (on my German Locale):</p> <pre><code>1 B 4,2 KB 41,4 MB 3,3 GB </code></pre> <hr> <p>Edit: I have opened an <a href="http://code.google.com/p/guava-libraries/issues/detail?id=428" rel="nofollow noreferrer">Issue requesting this functionality for Google Guava</a>. Perhaps someone would care to support it.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload