UnitConverter { public static String toSizeUnit(Long bytes, int scale) { if (bytes == null) { return "n/a"; } if (bytes < K) { return String.format("%4d", bytes); } if (bytes < M) { return String.format("%" + (scale == 0 ? 4 : 5 + scale) + '.' + scale + "fk", bytes * 1d / K); } if (bytes < G) { return String.format("%" + (scale == 0 ? 4 : 5 + scale) + '.' + scale + "fm", bytes * 1d / M); } if (bytes < T) { return String.format("%" + (scale == 0 ? 4 : 5 + scale) + '.' + scale + "fg", bytes * 1d / G); } return String.format("%" + (scale == 0 ? 4 : 5 + scale) + '.' + scale + "ft", bytes * 1d / T); }  static long toDurationMillis(String duration); static long toBytes(String size); static String toSizeUnit(Long bytes, int scale); static String toTimeUnit(long millis, int scale); static String toTimeWithMinorUnit(long millis);  }
@Test public void convertToSizeUnit() { assertThat(UnitConverter.toSizeUnit(966L, 0)).isEqualTo(" 966"); assertThat(UnitConverter.toSizeUnit(1522L, 0)).isEqualTo(" 1k"); assertThat(UnitConverter.toSizeUnit(1522L, 1)).isEqualTo(" 1.5k"); assertThat(UnitConverter.toSizeUnit(1024L * 1024 * 2 + 1024 * 200, 0)).isEqualTo(" 2m"); assertThat(UnitConverter.toSizeUnit(1024L * 1024 * 2 + 1024 * 600, 0)).isEqualTo(" 3m"); assertThat(UnitConverter.toSizeUnit(1024L * 1024 * 2 + 1024 * 140, 1)).isEqualTo(" 2.1m"); assertThat(UnitConverter.toSizeUnit(1024L * 1024 * 2 + 1024 * 160, 1)).isEqualTo(" 2.2m"); assertThat(UnitConverter.toSizeUnit(1024L * 1024 * 1024 * 2 + 1024 * 1024 * 200, 0)).isEqualTo(" 2g"); assertThat(UnitConverter.toSizeUnit(1024L * 1024 * 1024 * 2 + 1024 * 1024 * 200, 1)).isEqualTo(" 2.2g"); assertThat(UnitConverter.toSizeUnit(1024L * 1024 * 1024 * 1024 * 2 + 1024L * 1024 * 1024 * 200, 0)) .isEqualTo(" 2t"); assertThat(UnitConverter.toSizeUnit(1024L * 1024 * 1024 * 1024 * 2 + 1024L * 1024 * 1024 * 200, 1)) .isEqualTo(" 2.2t"); }