Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Java bytes to string helper
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class ByteStringer {
private static final String[] BYTES_UNITS = new String[] {"B", "KB", "MB", "GB", "TB"};
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = BigDecimal.valueOf(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
private static String bytesToString(Long bytes) {
double value = bytes;
double DIVIDER = 1024.0;
int unitIndex = 0;
while (unitIndex < BYTES_UNITS.length - 1 && value > DIVIDER) {
value = value / DIVIDER;
++unitIndex;
}
String number;
double rounded = round(value, 2);
int centides = (int) ((rounded % 1) * 100);
if(centides != 0) {
number = "" + rounded;
} else {
number = "" + (int) value;
}
return number + " " + BYTES_UNITS[Math.min(unitIndex, BYTES_UNITS.length - 1)];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment