ByteFormatter { public static String format(final long size, final Locale locale) { final StringBuffer buffer = new StringBuffer(); final NumberFormat byteFormat = NumberFormat.getNumberInstance(locale); byteFormat.setMaximumFractionDigits(2); byteFormat.setMinimumFractionDigits(2); if (size < s1kB) { buffer.append(size); } else if (size < s1MB) { int value = (int) (size) >> 10; buffer.append(value).append(" kB"); } else if (size < s1GB) { double d = ((double) size) / s1MB; byteFormat.format(d, buffer, new FieldPosition(0)).append(" MB"); } else if (size < s1TB) { double d = ((double) size) / s1GB; byteFormat.format(d, buffer, new FieldPosition(0)).append(" GB"); } else { double d = ((double) size) / s1TB; byteFormat.format(d, buffer, new FieldPosition(0)).append(" TB"); } return buffer.toString(); } private  ByteFormatter(); static String format(final long size, final Locale locale);  }
@Test public void testFormat() throws Exception { assertEquals("1000", ByteFormatter.format(1000L, new Locale("sv", "SE"))); assertEquals("1 kB", ByteFormatter.format(1200L, new Locale("sv", "SE"))); assertEquals("1 kB", ByteFormatter.format(2047L, new Locale("sv", "SE"))); assertEquals("2 kB", ByteFormatter.format(2048L, new Locale("sv", "SE"))); assertEquals("12 kB", ByteFormatter.format(12345L, new Locale("sv", "SE"))); assertEquals("120 kB", ByteFormatter.format(123456L, new Locale("sv", "SE"))); assertEquals("1,18 MB", ByteFormatter.format(1234567L, new Locale("sv", "SE"))); assertEquals("11,77 MB", ByteFormatter.format(12345678L, new Locale("sv", "SE"))); assertEquals("117,74 MB", ByteFormatter.format(123456789L, new Locale("sv", "SE"))); assertEquals("1,15 GB", ByteFormatter.format(1234567890L, new Locale("sv", "SE"))); assertEquals("11,50 GB", ByteFormatter.format(12345678901L, new Locale("sv", "SE"))); assertEquals("114,98 GB", ByteFormatter.format(123456789012L, new Locale("sv", "SE"))); assertEquals("1,12 TB", ByteFormatter.format(1234567890123L, new Locale("sv", "SE"))); }