Created
September 20, 2021 15:36
-
-
Save TheRolfFR/799885eefd6391ec348df12ea5718312 to your computer and use it in GitHub Desktop.
Java bytes to string helper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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