Format numbers work (#235)

Co-authored-by: Martin Robertz <[email protected]>
This commit is contained in:
Connor-ColensoandMartin Robertz authored and GitHub committed 2026-01-22 22:29:38 -05:00
1 parent 5b55a26ae5
commit 9445025082
18 files changed
+1676

No files matched your search

@@ -12,6 +12,11 @@ import com.gtnewhorizon.gtnhlib.block.BlockTestTintMul;
import com.gtnewhorizon.gtnhlib.blockstate.command.BlockStateCommand;
import com.gtnewhorizon.gtnhlib.blockstate.init.BlockPropertyInit;
import com.gtnewhorizon.gtnhlib.brigadier.BrigadierApi;
import com.gtnewhorizon.gtnhlib.chat.ChatComponentCustomRegistry;
import com.gtnewhorizon.gtnhlib.chat.customcomponents.ChatComponentEnergy;
import com.gtnewhorizon.gtnhlib.chat.customcomponents.ChatComponentFluid;
import com.gtnewhorizon.gtnhlib.chat.customcomponents.ChatComponentNumber;
import com.gtnewhorizon.gtnhlib.config.ConfigException;
import com.gtnewhorizon.gtnhlib.config.ConfigurationManager;
import com.gtnewhorizon.gtnhlib.eventbus.AutoEventBus;
import com.gtnewhorizon.gtnhlib.eventbus.EventBusSubscriber;
@@ -20,6 +25,8 @@ import com.gtnewhorizon.gtnhlib.keybind.SyncedKeybind;
import com.gtnewhorizon.gtnhlib.network.NetworkHandler;
import com.gtnewhorizon.gtnhlib.network.PacketMessageAboveHotbar;
import com.gtnewhorizon.gtnhlib.network.PacketViewDistance;
import com.gtnewhorizon.gtnhlib.util.numberformatting.NumberFormatConfig;
import com.gtnewhorizon.gtnhlib.util.numberformatting.NumberFormatUtil;
import cpw.mods.fml.common.event.FMLConstructionEvent;
import cpw.mods.fml.common.event.FMLInitializationEvent;
@@ -52,6 +59,19 @@ public class CommonProxy {
}
BlockPropertyInit.init();
ChatComponentCustomRegistry.register(ChatComponentNumber::new);
ChatComponentCustomRegistry.register(ChatComponentFluid::new);
ChatComponentCustomRegistry.register(ChatComponentEnergy::new);
// Number formatting config registration. Primarily aimed at client side, but does exist on server side
// as well, just in-case calls are made to number formatting.
try {
ConfigurationManager.registerConfig(NumberFormatConfig.class);
} catch (ConfigException e) {
throw new RuntimeException(e);
}
NumberFormatUtil.postConfiguration();
}
public void init(FMLInitializationEvent event) {
@@ -0,0 +1,49 @@
package com.gtnewhorizon.gtnhlib.chat;
import net.minecraft.util.ChatComponentStyle;
import net.minecraft.util.IChatComponent;
import org.jetbrains.annotations.NotNull;
import com.google.gson.JsonElement;
public abstract class AbstractChatComponentCustom extends ChatComponentStyle {
public abstract @NotNull JsonElement serialize();
public abstract void deserialize(@NotNull JsonElement jsonElement);
public abstract String getID(); // Unique ID across all mods. Make it good!
protected abstract AbstractChatComponentCustom copySelf();
@Override
public final boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
if (!super.equals(obj)) return false;
return serialize().equals(((AbstractChatComponentCustom) obj).serialize());
}
@Override
public final int hashCode() {
int result = super.hashCode();
result = 31 * result + serialize().hashCode();
return result;
}
@Override
public final IChatComponent createCopy() {
AbstractChatComponentCustom copy = copySelf();
copy.setChatStyle(getChatStyle().createShallowCopy());
for (IChatComponent sibling : getSiblings()) {
copy.appendSibling(sibling.createCopy());
}
return copy;
}
}
@@ -0,0 +1,42 @@
package com.gtnewhorizon.gtnhlib.chat;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;
public final class ChatComponentCustomRegistry {
private static final Map<String, Supplier<? extends AbstractChatComponentCustom>> CHAT_COMPONENT_REGISTRY = new ConcurrentHashMap<>();
private ChatComponentCustomRegistry() {}
/**
* Register a custom chat component using its no-arg constructor call. Your class MUST have this, or it will not
* compile.
*/
public static void register(Supplier<? extends AbstractChatComponentCustom> factory) {
AbstractChatComponentCustom instance = factory.get();
String id = instance.getID();
if (id == null || id.isEmpty()) {
throw new IllegalArgumentException("Chat component ID must be non-null and non-empty.");
}
if (CHAT_COMPONENT_REGISTRY.putIfAbsent(id, factory) != null) {
throw new IllegalArgumentException("Chat component with id '" + id + "' is already registered.");
}
}
/**
* Create a new instance of a registered custom chat component.
*/
public static AbstractChatComponentCustom get(String id) {
Supplier<? extends AbstractChatComponentCustom> factory = CHAT_COMPONENT_REGISTRY.get(id);
if (factory == null) {
throw new IllegalArgumentException(
String.format("Attempted to get '%s' from chat component registry, but it is not registered.", id));
}
return factory.get();
}
}
@@ -0,0 +1,50 @@
package com.gtnewhorizon.gtnhlib.chat.customcomponents;
import java.math.BigDecimal;
import org.jetbrains.annotations.NotNull;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.gtnewhorizon.gtnhlib.chat.AbstractChatComponentCustom;
import com.gtnewhorizon.gtnhlib.util.numberformatting.NumberFormatUtil;
public abstract class AbstractChatComponentNumber extends AbstractChatComponentCustom {
protected BigDecimal number = BigDecimal.ZERO;
public AbstractChatComponentNumber() {}
public AbstractChatComponentNumber(Number number) {
this.number = NumberFormatUtil.bigDecimalConverter(number);
}
protected abstract String formatNumber(Number value);
@Override
public final String getUnformattedTextForChat() {
return formatNumber(number);
}
@Override
public @NotNull JsonElement serialize() {
final JsonObject obj = new JsonObject();
serializeNumber(obj, number);
return obj;
}
@Override
public void deserialize(@NotNull JsonElement jsonElement) {
JsonObject obj = jsonElement.getAsJsonObject();
this.number = deserializeNumber(obj);
}
private void serializeNumber(@NotNull JsonObject obj, @NotNull BigDecimal num) {
obj.addProperty("number", num.stripTrailingZeros().toPlainString());
}
private BigDecimal deserializeNumber(@NotNull JsonObject obj) {
return new BigDecimal(obj.get("number").getAsString());
}
}
@@ -0,0 +1,32 @@
package com.gtnewhorizon.gtnhlib.chat.customcomponents;
import com.gtnewhorizon.gtnhlib.chat.AbstractChatComponentCustom;
import com.gtnewhorizon.gtnhlib.util.numberformatting.NumberFormatUtil;
@SuppressWarnings("unused")
public final class ChatComponentEnergy extends ChatComponentNumber {
public ChatComponentEnergy() {
super();
}
public ChatComponentEnergy(Number number) {
super(number);
}
@Override
protected String formatNumber(Number value) {
return NumberFormatUtil.formatEnergy(value);
}
@Override
public String getID() {
return "gtnhlib:ChatComponentEnergy";
}
@Override
protected AbstractChatComponentCustom copySelf() {
return new ChatComponentEnergy(number);
}
}
@@ -0,0 +1,38 @@
package com.gtnewhorizon.gtnhlib.chat.customcomponents;
import net.minecraftforge.fluids.FluidStack;
import com.gtnewhorizon.gtnhlib.chat.AbstractChatComponentCustom;
import com.gtnewhorizon.gtnhlib.util.numberformatting.NumberFormatUtil;
@SuppressWarnings("unused")
public final class ChatComponentFluid extends AbstractChatComponentNumber {
public ChatComponentFluid() {
super();
}
public ChatComponentFluid(Number number) {
super(number);
}
public ChatComponentFluid(FluidStack number) {
super(number.amount);
}
@Override
protected String formatNumber(Number value) {
return NumberFormatUtil.formatFluid(value);
}
@Override
public String getID() {
return "gtnhlib:ChatComponentFluid";
}
@Override
protected AbstractChatComponentCustom copySelf() {
return new ChatComponentFluid(number);
}
}
@@ -0,0 +1,32 @@
package com.gtnewhorizon.gtnhlib.chat.customcomponents;
import com.gtnewhorizon.gtnhlib.chat.AbstractChatComponentCustom;
import com.gtnewhorizon.gtnhlib.util.numberformatting.NumberFormatUtil;
@SuppressWarnings("unused")
public class ChatComponentNumber extends AbstractChatComponentNumber {
public ChatComponentNumber() {
super();
}
public ChatComponentNumber(Number number) {
super(number);
}
@Override
protected String formatNumber(Number value) {
return NumberFormatUtil.formatNumber(value);
}
@Override
public String getID() {
return "gtnhlib:ChatComponentNumber";
}
@Override
protected AbstractChatComponentCustom copySelf() {
return new ChatComponentNumber(number);
}
}
@@ -51,6 +51,8 @@ public enum Mixins implements IMixins {
ITEM_TRANSLUCENCY(new MixinBuilder("ItemRenderer & RenderItem ITranslucentItem support")
.addClientMixins("MixinItemRenderer_Translucency", "MixinRenderItem_Translucency").setPhase(Phase.EARLY)
.setApplyIf(() -> GTNHLibConfig.enableTranslucentItemRenders)),
CUSTOM_CHAT_COMPONENT_REGISTRATION(new MixinBuilder("Custom chat component registration")
.addCommonMixins("MixinIChatComponentSerializer").setPhase(Phase.EARLY)),
MULTI_RELEASE_JAR_FILTER(new MixinBuilder("Skip multi-release JAR entries in mod discovery")
.addCommonMixins("fml.MixinJarDiscoverer").setPhase(Phase.EARLY).addExcludedMod(TargetMods.LWJGL3IFY)),
PICK_BLOCK_TRAP(Side.CLIENT, "MixinMinecraft_PickBlockTrap"),
@@ -0,0 +1,108 @@
package com.gtnewhorizon.gtnhlib.mixins.early;
import java.lang.reflect.Type;
import net.minecraft.util.ChatStyle;
import net.minecraft.util.IChatComponent;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import com.google.gson.*;
import com.gtnewhorizon.gtnhlib.chat.AbstractChatComponentCustom;
import com.gtnewhorizon.gtnhlib.chat.ChatComponentCustomRegistry;
@Mixin(IChatComponent.Serializer.class)
public abstract class MixinIChatComponentSerializer {
@Unique
private static final String GTNHLIB_ID = "gtnhlib_id";
@Unique
private static final String GTNHLIB_PAYLOAD = "gtnhlib_payload";
// Vanilla helper that flattens ChatStyle fields onto the component JsonObject
@Shadow
private void func_150695_a(ChatStyle style, JsonObject object, JsonSerializationContext ctx) {}
@Inject(
method = "serialize(Lnet/minecraft/util/IChatComponent;Ljava/lang/reflect/Type;Lcom/google/gson/JsonSerializationContext;)Lcom/google/gson/JsonElement;",
at = @At("HEAD"),
cancellable = true)
private void gtnhlib$serializeCustom(IChatComponent component, Type type, JsonSerializationContext ctx,
CallbackInfoReturnable<JsonElement> cir) {
if (!(component instanceof AbstractChatComponentCustom custom)) {
return; // Leave vanilla to handle others stuff, e.g. ChatComponentText/Translation.
}
JsonObject root = new JsonObject();
// Custom tag + payload
root.addProperty(GTNHLIB_ID, custom.getID());
root.add(GTNHLIB_PAYLOAD, custom.serialize());
// vanilla style flattening
if (!component.getChatStyle().isEmpty()) {
this.func_150695_a(component.getChatStyle(), root, ctx);
}
// Vanilla siblings stored under ("extra")
if (!component.getSiblings().isEmpty()) {
JsonArray extra = new JsonArray();
for (IChatComponent sib : component.getSiblings()) {
// Use gson to serialize siblings so they can themselves be custom or vanilla
extra.add(ctx.serialize(sib, IChatComponent.class));
}
root.add("extra", extra);
}
cir.setReturnValue(root);
}
@Inject(
method = "deserialize(Lcom/google/gson/JsonElement;Ljava/lang/reflect/Type;Lcom/google/gson/JsonDeserializationContext;)Lnet/minecraft/util/IChatComponent;",
at = @At("HEAD"),
cancellable = true)
private void gtnhlib$deserializeCustom(JsonElement element, Type type, JsonDeserializationContext ctx,
CallbackInfoReturnable<IChatComponent> cir) {
if (!element.isJsonObject()) return;
JsonObject obj = element.getAsJsonObject();
if (!obj.has(GTNHLIB_ID)) return; // Not a custom registration, let vanilla handle it.
JsonElement idEl = obj.get(GTNHLIB_ID);
if (idEl == null || !idEl.isJsonPrimitive()) {
throw new JsonParseException("gtnhlib_id must be a JSON string");
}
String id = idEl.getAsString();
AbstractChatComponentCustom chatComponent = ChatComponentCustomRegistry.get(id);
JsonElement payload = obj.get(GTNHLIB_PAYLOAD);
if (payload == null) {
throw new JsonParseException("Missing gtnhlib_payload for id: " + id);
}
// Fill the custom component.
chatComponent.deserialize(payload);
// Vanilla siblings
if (obj.has("extra")) {
JsonArray extra = obj.getAsJsonArray("extra");
if (extra.size() <= 0) {
throw new JsonParseException("Unexpected empty array of components");
}
for (int i = 0; i < extra.size(); i++) {
chatComponent.appendSibling(ctx.deserialize(extra.get(i), IChatComponent.class));
}
}
// Vanilla style (deserialize ChatStyle from the whole object)
chatComponent.setChatStyle(ctx.deserialize(element, ChatStyle.class));
cir.setReturnValue(chatComponent);
}
}
@@ -0,0 +1,12 @@
package com.gtnewhorizon.gtnhlib.util.numberformatting;
import java.math.BigDecimal;
public final class Constants {
public static final BigDecimal BD_THOUSAND = BigDecimal.valueOf(1_000);
public static final BigDecimal BD_MILLION = BigDecimal.valueOf(1_000_000);
public static final BigDecimal BD_BILLION = BigDecimal.valueOf(1_000_000_000);
public static final BigDecimal BD_TRILLION = BigDecimal.valueOf(1_000_000_000_000L);
public static final BigDecimal BD_QUADRILLION = BigDecimal.valueOf(1_000_000_000_000_000L);
}
@@ -0,0 +1,113 @@
package com.gtnewhorizon.gtnhlib.util.numberformatting;
import static com.gtnewhorizon.gtnhlib.util.numberformatting.Constants.BD_THOUSAND;
import static com.gtnewhorizon.gtnhlib.util.numberformatting.NumberFormatUtil.formatNumber;
import java.math.BigDecimal;
import java.math.MathContext;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Arrays;
import java.util.Locale;
import com.gtnewhorizon.gtnhlib.util.numberformatting.options.NumberOptionsBase;
public enum ExponentialFormat {
SCIENTIFIC {
@Override
String format(BigDecimal v, NumberOptionsBase<?> options) {
return formatScientificStandard(v, options);
}
},
ENGINEERING {
@Override
String format(BigDecimal v, NumberOptionsBase<?> options) {
return formatScientificEngineering(v, options);
}
},
POWER_OF_TEN {
@Override
String format(BigDecimal v, NumberOptionsBase<?> options) {
return formatScientificPowerOfTen(v, options);
}
};
abstract String format(BigDecimal value, NumberOptionsBase<?> options);
public static ExponentialFormat parse(String raw) {
try {
return ExponentialFormat.valueOf(raw.trim().toUpperCase(Locale.ROOT));
} catch (Exception e) {
throw new IllegalStateException(
"Invalid scientific format '" + raw + "'. Valid values: " + Arrays.toString(values()));
}
}
private static String formatScientificStandard(BigDecimal value, NumberOptionsBase<?> options) {
BigDecimal rounded = value.round(new MathContext(options.getDecimalPlaces() + 1, options.getRoundingMode()));
int fractionalDigits = Math.max(1, options.getDecimalPlaces());
Locale locale = Locale.getDefault(Locale.Category.FORMAT);
DecimalFormatSymbols symbols = new DecimalFormatSymbols(locale);
symbols.setExponentSeparator("e");
StringBuilder pattern = new StringBuilder("0.");
for (int i = 0; i < fractionalDigits; i++) {
pattern.append('#');
}
pattern.append("E0");
DecimalFormat df = new DecimalFormat(pattern.toString(), symbols);
df.setGroupingUsed(false);
df.setRoundingMode(options.getRoundingMode());
return df.format(rounded);
}
private static String formatScientificEngineering(BigDecimal value, NumberOptionsBase<?> options) {
BigDecimal abs = value.abs();
int base10Exponent = abs.precision() - 1 - abs.scale();
int engExp = Math.floorDiv(base10Exponent, 3) * 3;
BigDecimal mantissa = value.movePointLeft(engExp);
mantissa = mantissa.setScale(options.getDecimalPlaces(), options.getRoundingMode());
// rounding can push mantissa to 1000 -> re-normalise to keep engineering form
BigDecimal absMantissa = mantissa.abs();
if (absMantissa.compareTo(BD_THOUSAND) >= 0) {
mantissa = mantissa.movePointLeft(3).setScale(options.getDecimalPlaces(), options.getRoundingMode());
engExp += 3;
}
// Strip trailing zeros
mantissa = mantissa.stripTrailingZeros();
// Shove small number back through itself, recursive, but easier to handle.
return formatNumber(mantissa, options.toFormatOptions()) + "e" + engExp;
}
private static String formatScientificPowerOfTen(BigDecimal value, NumberOptionsBase<?> options) {
BigDecimal rounded = value.round(new MathContext(options.getDecimalPlaces() + 1, options.getRoundingMode()));
int exponent = rounded.precision() - 1 - rounded.scale();
BigDecimal mantissa = rounded.movePointLeft(exponent);
Locale locale = Locale.getDefault(Locale.Category.FORMAT);
DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
DecimalFormat df = new DecimalFormat();
df.setDecimalFormatSymbols(symbols);
df.setGroupingUsed(false);
df.setRoundingMode(options.getRoundingMode());
df.setMaximumFractionDigits(Math.max(1, options.getDecimalPlaces()));
return df.format(mantissa) + "*10^" + exponent;
}
}
@@ -0,0 +1,31 @@
package com.gtnewhorizon.gtnhlib.util.numberformatting;
import com.gtnewhorizon.gtnhlib.config.Config;
@Config(modid = "gtnhlib", category = "number_formatting", filename = "gtnhlib-number-formatting")
public final class NumberFormatConfig {
@Config.Comment({ "Completely disables ALL number formatting, all numbers will show 'raw', i.e. 1000000", })
@Config.DefaultBoolean(false)
public static boolean disableFormattedNotation = false;
@Config.Comment({
"Completely disables exponential notation. No scientific, standard form or engineering notation." })
@Config.DefaultBoolean(false)
public static boolean globalDisableExponentialNotation = false;
@Config.Comment({ "True indicates to use mB, false uses GregTech L." })
@Config.DefaultBoolean(true)
public static boolean useForgeFluidMillibuckets = true;
@Config.Comment({ "Controls how very large numbers are rendered when scientific notation is used.",
" SCIENTIFIC – Standard scientific notation (e.g. 1.23e12)",
" ENGINEERING – Engineering notation with exponent in multiples of 3 (e.g. 123e9)",
" POWER_OF_TEN – Power-of-ten notation using explicit multiplication (e.g. 1.23*10^12)",
"Invalid values will cause the game to fail fast with an error." })
@Config.DefaultString("SCIENTIFIC")
public static String formatPattern = "SCIENTIFIC";
@Config.Ignore
public static ExponentialFormat EXPONENTIAL_FORMAT = ExponentialFormat.SCIENTIFIC;
}
@@ -0,0 +1,297 @@
package com.gtnewhorizon.gtnhlib.util.numberformatting;
import static com.gtnewhorizon.gtnhlib.util.numberformatting.Constants.BD_BILLION;
import static com.gtnewhorizon.gtnhlib.util.numberformatting.Constants.BD_MILLION;
import static com.gtnewhorizon.gtnhlib.util.numberformatting.Constants.BD_QUADRILLION;
import static com.gtnewhorizon.gtnhlib.util.numberformatting.Constants.BD_THOUSAND;
import static com.gtnewhorizon.gtnhlib.util.numberformatting.Constants.BD_TRILLION;
import static com.gtnewhorizon.gtnhlib.util.numberformatting.NumberFormatConfig.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
import net.minecraftforge.fluids.FluidStack;
import com.gtnewhorizon.gtnhlib.util.numberformatting.options.CompactOptions;
import com.gtnewhorizon.gtnhlib.util.numberformatting.options.FormatOptions;
import com.gtnewhorizon.gtnhlib.util.numberformatting.options.NumberOptionsBase;
@SuppressWarnings("unused")
public final class NumberFormatUtil {
/* ========================= Formatters ========================= */
private NumberFormatUtil() {}
/* ========================= Main Formatter ========================= */
public static String formatNumber(Number value) {
return formatNumber(value, new FormatOptions());
}
public static String formatNumber(Number value, FormatOptions options) {
String special = handleSpecialCases(value);
if (special != null) return special;
BigDecimal val = bigDecimalConverter(value);
BigDecimal abs = val.abs();
if (abs.signum() == 0) return "0";
// Exponential for more than 1T by default
if (isExponentialFormattingEnabled(abs, options)) {
return formatExponential(val, options);
}
// Plain locale formatting
return centralFormatter(getDefaultDecimalFormatter(options).format(val));
}
/* ========================= Compact Numbers ========================= */
public static String formatNumberCompact(Number value) {
return formatNumberCompact(value, new CompactOptions());
}
/**
* Compact / abbreviated formatting.
* <p>
* Below the abbreviation threshold becomes standard formatting. Between threshold and 1T becomes abbreviated
* (K/M/B), greater than 1T becomes exponential. Options objects can modify this behaviour.
*/
public static String formatNumberCompact(Number value, CompactOptions options) {
String special = handleSpecialCases(value);
if (special != null) return special;
BigDecimal val = bigDecimalConverter(value);
BigDecimal abs = val.abs();
if (abs.signum() == 0) return "0";
// Below threshold, do exact formatting
if (abs.compareTo(options.getCompactThreshold()) < 0) {
return formatNumber(value, options.toFormatOptions());
}
// More than 1T, do exponential.
if (isExponentialFormattingEnabled(abs, options)) {
return formatExponential(val, options);
}
// Abbreviated (1K, 2.5M etc)
return abbreviate(val, options);
}
/* ========================= Abbreviation ========================= */
private static String abbreviate(BigDecimal value, NumberOptionsBase<?> options) {
BigDecimal abs = value.abs();
BigDecimal divisor;
String suffix;
if (abs.compareTo(BD_QUADRILLION) >= 0) {
divisor = BD_QUADRILLION;
suffix = "Q";
} else if (abs.compareTo(BD_TRILLION) >= 0) {
divisor = BD_TRILLION;
suffix = "T";
} else if (abs.compareTo(BD_BILLION) >= 0) {
divisor = BD_BILLION;
suffix = "B";
} else if (abs.compareTo(BD_MILLION) >= 0) {
divisor = BD_MILLION;
suffix = "M";
} else {
divisor = BD_THOUSAND;
suffix = "K";
}
BigDecimal scaled = value.divide(divisor, MathContext.UNLIMITED);
int dp = options.getDecimalPlaces();
RoundingMode rm = options.getRoundingMode();
BigDecimal rounded = scaled.setScale(dp, rm);
// Prevent unit rollover caused only by rounding:
// If abs(value) is still below the next threshold, do not allow rounded to reach 1000.
BigDecimal nextThreshold = divisor.multiply(BD_THOUSAND);
if (abs.compareTo(nextThreshold) < 0 && rounded.abs().compareTo(BD_THOUSAND) >= 0) {
BigDecimal step = BigDecimal.ONE.scaleByPowerOfTen(-dp); // 10^-dp (works for dp <= 0 too)
BigDecimal maxAbs = BD_THOUSAND.subtract(step).setScale(dp, RoundingMode.UNNECESSARY);
rounded = (rounded.signum() < 0) ? maxAbs.negate() : maxAbs;
}
rounded = rounded.stripTrailingZeros();
return formatNumber(rounded, options.toFormatOptions()) + suffix;
}
/* ========================= Exponential ========================= */
private static String formatExponential(BigDecimal value, NumberOptionsBase<?> options) {
return EXPONENTIAL_FORMAT.format(value, options);
}
/* ========================= Fluids ========================= */
public static String getFluidUnit() {
return useForgeFluidMillibuckets ? "mB" : "L";
}
public static String formatFluid(Number value) {
return formatFluid(value, new FormatOptions());
}
public static String formatFluid(Number value, FormatOptions options) {
return formatNumber(value, options) + " " + getFluidUnit();
}
public static String formatFluidCompact(Number value) {
return formatFluidCompact(value, new CompactOptions());
}
public static String formatFluidCompact(Number value, CompactOptions options) {
return formatNumberCompact(value, options) + " " + getFluidUnit();
}
public static String formatFluid(FluidStack stack) {
return formatFluid(stack.amount);
}
/* ========================= Energy ========================= */
public static String getEnergyUnit() {
return "EU";
}
public static String formatEnergy(Number value) {
return formatEnergy(value, new FormatOptions());
}
public static String formatEnergy(Number value, FormatOptions options) {
return formatNumber(value, options) + " " + getEnergyUnit();
}
public static String formatEnergyCompact(Number value, CompactOptions options) {
return formatNumberCompact(value, options) + " " + getEnergyUnit();
}
public static String formatEnergyCompact(Number value) {
return formatEnergyCompact(value, new CompactOptions());
}
/* ========================= Internals ========================= */
private static String rawNumberToString(Number value) {
if (value instanceof BigDecimal bd) {
// It seems BigDecimal.toString() may emit exponential notation, but
// toPlainString() never does.
return bd.toPlainString();
}
if (value instanceof BigInteger) {
return value.toString();
}
if (value instanceof Double || value instanceof Float) {
double d = value.doubleValue();
// toPlainString avoids exponent notation.
return BigDecimal.valueOf(d).stripTrailingZeros().toPlainString();
}
// Common wrappers
if (value instanceof Byte || value instanceof Short || value instanceof Integer || value instanceof Long) {
return Long.toString(value.longValue());
}
// Fallback: best effort was made!
return value.toString();
}
private static boolean isExponentialFormattingEnabled(BigDecimal absValue, NumberOptionsBase<?> options) {
// Global flag disables exponential formatting entirely
boolean disabledGlobally = globalDisableExponentialNotation;
// Whether this specific number qualifies for exponential formatting
boolean aboveThreshold = absValue.compareTo(options.getExponentialThreshold()) >= 0;
// Whether exponential formatting is enabled for this option
boolean enabledInOptions = options.isExponentialFormattingEnabled();
// Exponential formatting is enabled only if all conditions are true
return !disabledGlobally && enabledInOptions && aboveThreshold;
}
private static DecimalFormat getDefaultDecimalFormatter(NumberOptionsBase<?> options) {
Locale locale = Locale.getDefault(Locale.Category.FORMAT);
DecimalFormatSymbols symbols = DecimalFormatSymbols.getInstance(locale);
DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(locale);
df.setDecimalFormatSymbols(symbols);
df.setGroupingUsed(true);
df.setMaximumFractionDigits(options.getDecimalPlaces());
df.setRoundingMode(options.getRoundingMode());
return df;
}
private static String handleSpecialCases(Number value) {
if (value == null) return "NULL";
if (value instanceof Double || value instanceof Float) {
double d = value.doubleValue();
if (Double.isNaN(d)) return "NaN";
if (Double.isInfinite(d)) return d > 0 ? "Infinity" : "-Infinity";
}
if (disableFormattedNotation) return rawNumberToString(value);
return null; // Returning null signals no special case needed.
}
private static String centralFormatter(String s) {
s = s.replace("\u202F", " ");
s = s.replace("\u00A0", " ");
return s;
}
public static void postConfiguration() {
EXPONENTIAL_FORMAT = ExponentialFormat.parse(formatPattern);
}
public static BigDecimal bigDecimalConverter(Number number) {
if (number == null) {
throw new IllegalArgumentException("Number cannot be null");
}
if (number instanceof BigDecimal bd) {
return bd;
}
if (number instanceof BigInteger bi) {
return new BigDecimal(bi);
}
// Preserve exact integer values (avoids > 2^53 precision issues)
if (number instanceof Byte || number instanceof Short || number instanceof Integer || number instanceof Long) {
return BigDecimal.valueOf(number.longValue());
}
// Fallback: floating-point conversion
double d = number.doubleValue();
if (Double.isNaN(d)) {
throw new IllegalArgumentException("Cannot convert NaN to BigDecimal.");
}
if (Double.isInfinite(d)) {
throw new IllegalArgumentException("Cannot convert Infinity to BigDecimal.");
}
return BigDecimal.valueOf(d);
}
}
@@ -0,0 +1,56 @@
package com.gtnewhorizon.gtnhlib.util.numberformatting.options;
import static com.gtnewhorizon.gtnhlib.util.numberformatting.Constants.BD_THOUSAND;
import java.math.BigDecimal;
import com.gtnewhorizon.gtnhlib.util.numberformatting.NumberFormatUtil;
@SuppressWarnings("unchecked")
public final class CompactOptions extends NumberOptionsBase<CompactOptions> {
private BigDecimal compactThreshold = BD_THOUSAND;
public CompactOptions() {}
// ---------- Setters ----------
@Override
public CompactOptions setExponentialThreshold(Number number) {
BigDecimal value = NumberFormatUtil.bigDecimalConverter(number);
if (value.signum() < 0) throw new IllegalArgumentException("Scientific threshold must be >= 0");
// Prevent conflict with compact threshold.
// Compact must *always* be lower than the scientific threshold, or configuration becomes inconsistent.
BigDecimal currentCompact = getCompactThreshold();
if (value.compareTo(currentCompact) <= 0) {
throw new IllegalArgumentException(
"Scientific threshold must be strictly greater than compact threshold (" + currentCompact + ")");
}
super.setExponentialThreshold(value);
return this;
}
public CompactOptions setCompactThreshold(Number number) {
BigDecimal value = NumberFormatUtil.bigDecimalConverter(number);
if (value.signum() < 0) throw new IllegalArgumentException("Compact threshold must be >= 0");
// Prevent conflict with scientific threshold.
// Compact must *always* be lower than the scientific threshold, or configuration becomes inconsistent.
BigDecimal currentScientific = getExponentialThreshold();
if (value.compareTo(currentScientific) >= 0) {
throw new IllegalArgumentException(
"Compact threshold must be strictly less than scientific threshold (" + currentScientific + ")");
}
this.compactThreshold = value;
return this;
}
// ---------- Getters ----------
public BigDecimal getCompactThreshold() {
return compactThreshold;
}
}
@@ -0,0 +1,7 @@
package com.gtnewhorizon.gtnhlib.util.numberformatting.options;
@SuppressWarnings("unused")
public final class FormatOptions extends NumberOptionsBase<FormatOptions> {
public FormatOptions() {}
}
@@ -0,0 +1,106 @@
package com.gtnewhorizon.gtnhlib.util.numberformatting.options;
import static com.gtnewhorizon.gtnhlib.util.numberformatting.Constants.BD_TRILLION;
import java.math.BigDecimal;
import java.math.RoundingMode;
import com.gtnewhorizon.gtnhlib.util.numberformatting.NumberFormatUtil;
@SuppressWarnings({ "unchecked", "unused" })
public abstract class NumberOptionsBase<T extends NumberOptionsBase<T>> {
private int decimalPlaces = 2;
private BigDecimal exponentialThreshold = BD_TRILLION;
private boolean disableExponentialFormatting = false;
private RoundingMode roundingMode = RoundingMode.HALF_UP;
protected NumberOptionsBase() {}
// ---------- Setters ----------
public T setDecimalPlaces(int decimalPlaces) {
if (decimalPlaces < 0) throw new IllegalArgumentException("Decimal places must be >= 0");
this.decimalPlaces = decimalPlaces;
return (T) this;
}
public T setExponentialThreshold(Number number) {
if (number == null) throw new IllegalArgumentException("Number cannot be null");
BigDecimal value = NumberFormatUtil.bigDecimalConverter(number);
if (value.signum() < 0) throw new IllegalArgumentException("Exponential threshold must be >= 0");
this.exponentialThreshold = value.abs();
return (T) this;
}
public T disableExponentialFormatting() {
this.disableExponentialFormatting = true;
return (T) this;
}
public T enableExponentialFormatting() {
this.disableExponentialFormatting = false;
return (T) this;
}
public T setRoundingMode(RoundingMode roundingMode) {
this.roundingMode = roundingMode;
return (T) this;
}
// ---------- Getters ----------
public int getDecimalPlaces() {
return decimalPlaces;
}
public BigDecimal getExponentialThreshold() {
return exponentialThreshold;
}
public boolean isExponentialFormattingDisabled() {
return disableExponentialFormatting == true;
}
public boolean isExponentialFormattingEnabled() {
return disableExponentialFormatting == false;
}
public RoundingMode getRoundingMode() {
return roundingMode;
}
// ---------- Converters ----------
public FormatOptions toFormatOptions() {
FormatOptions options = new FormatOptions();
options.setExponentialThreshold(exponentialThreshold);
options.setDecimalPlaces(decimalPlaces);
options.setRoundingMode(roundingMode);
if (disableExponentialFormatting) {
options.disableExponentialFormatting();
} else {
options.enableExponentialFormatting();
}
return options;
}
public CompactOptions toCompactOptions() {
CompactOptions options = new CompactOptions();
options.setExponentialThreshold(exponentialThreshold);
options.setDecimalPlaces(decimalPlaces);
options.setRoundingMode(roundingMode);
if (disableExponentialFormatting) {
options.disableExponentialFormatting();
} else {
options.enableExponentialFormatting();
}
return options;
}
}