API Surface (4)
Unit getLargest(final long bytes)
double convertTo(final long bytes, final Unit unit)
String humanReadable(final long bytes)
String humanReadable(final long bytes, final Unit unit)
Full Source
Unit.java49 lines · Minecraft 26.3 · verbatim
| 1 | package com.mojang.realmsclient;
|
| 2 |
|
| 3 | import java.util.Locale;
|
| 4 | import net.fabricmc.api.EnvType;
|
| 5 | import net.fabricmc.api.Environment;
|
| 6 |
|
| 7 | @Environment(EnvType.CLIENT)
|
| 8 | public enum Unit {
|
| 9 | B,
|
| 10 | KB,
|
| 11 | MB,
|
| 12 | GB;
|
| 13 |
|
| 14 | private static final int BASE_UNIT = 1024;
|
| 15 |
|
| 16 | public static Unit getLargest(final long bytes) {
|
| 17 | if (bytes < 1024L) {
|
| 18 | return B;
|
| 19 | }
|
| 20 |
|
| 21 | try {
|
| 22 | int exp = (int)(Math.log(bytes) / Math.log(1024.0));
|
| 23 | String pre = String.valueOf("KMGTPE".charAt(exp - 1));
|
| 24 | return valueOf(pre + "B");
|
| 25 | } catch (Exception ignored) {
|
| 26 | return GB;
|
| 27 | }
|
| 28 | }
|
| 29 |
|
| 30 | public static double convertTo(final long bytes, final Unit unit) {
|
| 31 | return unit == B ? bytes : bytes / Math.pow(1024.0, unit.ordinal());
|
| 32 | }
|
| 33 |
|
| 34 | public static String humanReadable(final long bytes) {
|
| 35 | int unit = 1024;
|
| 36 | if (bytes < 1024L) {
|
| 37 | return bytes + " B";
|
| 38 | }
|
| 39 |
|
| 40 | int exp = (int)(Math.log(bytes) / Math.log(1024.0));
|
| 41 | String pre = "KMGTPE".charAt(exp - 1) + "";
|
| 42 | return String.format(Locale.ROOT, "%.1f %sB", bytes / Math.pow(1024.0, exp), pre);
|
| 43 | }
|
| 44 |
|
| 45 | public static String humanReadable(final long bytes, final Unit unit) {
|
| 46 | return String.format(Locale.ROOT, "%." + (unit == GB ? "1" : "0") + "f %s", convertTo(bytes, unit), unit.name());
|
| 47 | }
|
| 48 | }
|
| 49 |
|
Decompiled Minecraft 26.3 source of Unit (com/mojang/realmsclient/Unit.java) with Mojang official mappings, stored verbatim on the site.