Skip to content

Instantly share code, notes, and snippets.

@TheRolfFR
Created September 20, 2021 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TheRolfFR/799885eefd6391ec348df12ea5718312 to your computer and use it in GitHub Desktop.
Save TheRolfFR/799885eefd6391ec348df12ea5718312 to your computer and use it in GitHub Desktop.
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