Add Coal Cents economy
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
package com.librewiki.coalgov.util;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
|
||||
public final class CoalMoney {
|
||||
public static final long CENTS_PER_COAL = 100L;
|
||||
|
||||
private CoalMoney() {
|
||||
}
|
||||
|
||||
public static long fromCoal(double coal) {
|
||||
return Math.round(coal * CENTS_PER_COAL);
|
||||
}
|
||||
|
||||
public static long fromCoalConfig(double coal) {
|
||||
return Math.max(0L, fromCoal(coal));
|
||||
}
|
||||
|
||||
public static String format(long cents) {
|
||||
boolean negative = cents < 0L;
|
||||
long absolute = Math.abs(cents);
|
||||
long coal = absolute / CENTS_PER_COAL;
|
||||
long coalCents = absolute % CENTS_PER_COAL;
|
||||
String prefix = negative ? "-" : "";
|
||||
if (coal > 0L && coalCents > 0L) {
|
||||
return prefix + coal + " coal " + coalCents + "cc";
|
||||
}
|
||||
if (coal > 0L) {
|
||||
return prefix + coal + " coal";
|
||||
}
|
||||
return prefix + coalCents + "cc";
|
||||
}
|
||||
|
||||
public static long parsePositive(String raw) {
|
||||
long amount = parse(raw);
|
||||
return amount > 0L ? amount : -1L;
|
||||
}
|
||||
|
||||
public static long parse(String raw) {
|
||||
if (raw == null) {
|
||||
return -1L;
|
||||
}
|
||||
String normalized = raw.trim().toLowerCase();
|
||||
if (normalized.isEmpty() || normalized.startsWith("-")) {
|
||||
return -1L;
|
||||
}
|
||||
try {
|
||||
if (normalized.endsWith("cc")) {
|
||||
return Long.parseLong(normalized.substring(0, normalized.length() - 2));
|
||||
}
|
||||
if (normalized.endsWith("c")) {
|
||||
return parseDecimalCoal(normalized.substring(0, normalized.length() - 1));
|
||||
}
|
||||
if (normalized.endsWith("coal")) {
|
||||
return parseDecimalCoal(normalized.substring(0, normalized.length() - 4));
|
||||
}
|
||||
return parseDecimalCoal(normalized);
|
||||
} catch (ArithmeticException | NumberFormatException exception) {
|
||||
return -1L;
|
||||
}
|
||||
}
|
||||
|
||||
private static long parseDecimalCoal(String raw) {
|
||||
BigDecimal coal = new BigDecimal(raw.trim());
|
||||
BigDecimal cents = coal.multiply(BigDecimal.valueOf(CENTS_PER_COAL));
|
||||
return cents.setScale(0, RoundingMode.HALF_UP).longValueExact();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user