Here you can find the source of formatBytes(final long bytes)
Parameter | Description |
---|---|
bytes | a parameter |
public static String formatBytes(final long bytes)
//package com.java2s; //License from project: Open Source License import java.math.BigDecimal; import java.text.NumberFormat; import java.util.Locale; public class Main { public static final int KILO_BYTES = 1024; public static final BigDecimal KB_BD = new BigDecimal(KILO_BYTES); public static final int MEGA_BYTES = KILO_BYTES * 1024; public static final BigDecimal MB_BD = new BigDecimal(MEGA_BYTES); public static final int GIGA_BYTES = MEGA_BYTES * 1024; public static final BigDecimal GB_BD = new BigDecimal(GIGA_BYTES); /**/*from ww w . j a v a2 s . co m*/ * Pretty output of bytes, "1023 bytes", "1.1 kb", "523 kb", "1.7 Mb", "143 * Gb" etc. * * @param bytes * @return */ public static String formatBytes(final long bytes) { if (bytes < KILO_BYTES) { return String.valueOf(bytes) + " bytes"; } if (bytes < MEGA_BYTES) { BigDecimal no = new BigDecimal(bytes).divide(KB_BD, 1, BigDecimal.ROUND_HALF_UP); if (no.longValue() >= 100) { no = no.setScale(0, BigDecimal.ROUND_HALF_UP); } return NumberFormat.getInstance(Locale.getDefault()).format(no) + " kb"; } if (bytes < GIGA_BYTES) { BigDecimal no = new BigDecimal(bytes).divide(MB_BD, 1, BigDecimal.ROUND_HALF_UP); if (no.longValue() >= 100) { no = no.setScale(0, BigDecimal.ROUND_HALF_UP); } return NumberFormat.getInstance(Locale.getDefault()).format(no) + " Mb"; } BigDecimal no = new BigDecimal(bytes).divide(GB_BD, 1, BigDecimal.ROUND_HALF_UP); if (no.longValue() >= 100) { no = no.setScale(0, BigDecimal.ROUND_HALF_UP); } return NumberFormat.getInstance(Locale.getDefault()).format(no) + " Gb"; } }