Note that there are some explanatory texts on larger screens.

plurals
  1. POFormat file size as MB, GB etc
    text
    copied!<p>I need to display a file size as String using sensible units.</p> <p>e.g.</p> <pre><code>1L ==&gt; "1 B"; 1024L ==&gt; "1 KB"; 2537253L ==&gt; "2.3 MB" </code></pre> <p>etc.</p> <p>I found <a href="https://stackoverflow.com/questions/801935/formatting-file-sizes-in-java-jstl">this previous answer</a>, which I didn't find satisfactory</p> <p>I have come up with my own solution which has similar shortcomings:</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 String.format("%.1f %s", Double.valueOf(result), unit); } </code></pre> <p>The main problem is my limited knowledge of Decimalformat and / or String.format. I would like 1024L, 1025L etc to map to <code>1 KB</code> rather than <code>1.0 KB</code>.</p> <p>So, two possibilities:</p> <ol> <li>I would prefer a good out-of-the-box solution in a public library like apache commons or google guava.</li> <li>If there isn't, can someone show me how to get rid of the '.0' part (without resorting to string replacement and regex, I can do that myself)</li> </ol>
 

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