Skip to content

Instantly share code, notes, and snippets.

@Azoraqua
Created November 10, 2017 13:41
Show Gist options
  • Save Azoraqua/8e51e2b67db6dcdde451c8bc49375d84 to your computer and use it in GitHub Desktop.
Save Azoraqua/8e51e2b67db6dcdde451c8bc49375d84 to your computer and use it in GitHub Desktop.
public class NumberFormatTest {
private static enum Unit {
K(4, 6, "K"),
M(7, 9, "M"),
B(9, 12, "B");
private int min, max;
private String unitChar;
Unit(int min, int max, String unitChar) {
this.min = min;
this.max = max;
this.unitChar = unitChar;
}
}
public static void main(String[] args) {
DecimalFormat numberFormat = new DecimalFormat("#,###,###,###");
for (long l : new long[] {
1_000_000_000,
1_000_000,
1_000,
100,
10,
1
}) {
String formatted = numberFormat.format(l) + " " + NumberFormatTest.formatUnit(l);
System.out.println(String.format("Input: %s | Output: $%s", l, formatted));
}
}
private static String formatUnit(long l) {
for(Unit unit : Unit.values()) {
int length = String.valueOf(l).length();
if(length >= unit.min && length <= unit.max) {
return unit.unitChar;
}
}
return "";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment