Size { public static String toHumanSize(long sizeInBytes) { if (sizeInBytes < 0) { throw new IllegalArgumentException(String.format("Negative size: %d", sizeInBytes)); } if (sizeInBytes < K) { return String.format("%d B", sizeInBytes); } float size = 0.0f; String suffix = "PB"; for (int i = 0, l = SIZE_UNITS.length; i < l; i++) { Pair<Long, String> sizeUnit = SIZE_UNITS[i]; if (sizeInBytes >= sizeUnit.first) { size = (float)sizeInBytes / sizeUnit.first; suffix = sizeUnit.second; break; } } return String.format((size % 1.0f == 0) ? "%.0f %s" : "%.1f %s", size, suffix); } private  Size(); static String toHumanSize(long sizeInBytes); static long parseSize(String humanSize); static long parseSizeToMegabytes(String humanSize);  }
@Test public void testToHumanSize() { Assert.assertEquals(Size.toHumanSize(1024), "1 kB"); Assert.assertEquals(Size.toHumanSize(1000), "1000 B"); Assert.assertEquals(Size.toHumanSize(1024 * 1024), "1 MB"); Assert.assertEquals(Size.toHumanSize(5 * 1024 * 1024), "5 MB"); Assert.assertEquals(Size.toHumanSize(5L * 1024 * 1024 * 1024), "5 GB"); Assert.assertEquals(Size.toHumanSize(7539480), "7" + sep + "2 MB"); Assert.assertEquals(Size.toHumanSize(10226124), "9" + sep + "8 MB"); }