Skip to content

Instantly share code, notes, and snippets.

@kylepls
Created March 22, 2017 19:54
Show Gist options
  • Save kylepls/7e6c91728edaaafed77c93a6cfff0341 to your computer and use it in GitHub Desktop.
Save kylepls/7e6c91728edaaafed77c93a6cfff0341 to your computer and use it in GitHub Desktop.
Used for formatting SI units
package com.arcadianmc.skyblock.utils;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.experimental.UtilityClass;
/**
* Created by Kyle on 3/22/2017.
*/
@UtilityClass
public class SIUtils {
public static String formatSi(double amount) {
int order = 0;
while (amount > 1000.0) {
amount /= 1000.0;
order += 3;
}
while (amount < 1.0) {
amount *= 1000.0;
order -= 3;
}
return (amount + SISignifier.getSuffix(order)).replaceFirst("\\.0[a-zA-Z]", "");
}
@AllArgsConstructor
private enum SISignifier {
YOTTA(24, "Y"),
ZETTA(21, "Z"),
EXA(18, "E"),
PETA(15, "P"),
TERA(12, "T"),
GIGA(9, "G"),
MEGA(6, "M"),
KILO(3, "k"),
HECTO(2, "h"),
DEKA(1, "da"),
NONE(0, ""),
DECI(-1, "d"),
CENTI(-2, "c"),
MILLI(-3, "m"),
MICRO(-6, "µ"),
NANO(-9, "n"),
PICO(-12, "p"),
FEMTO(-15, "f"),
ATTO(-18, "a"),
ZEPTO(-21, "z"),
YOCTO(-24, "y");
@Getter
private final int factor;
@Getter
private final String suffix;
private static String getSuffix(int exp) {
for (SISignifier siSignifier : SISignifier.values()) {
if (siSignifier.getFactor() == exp) {
return siSignifier.getSuffix();
}
}
throw new IllegalArgumentException("No suffix for 10^" + exp);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment