Created
November 10, 2017 13:41
-
-
Save Azoraqua/8e51e2b67db6dcdde451c8bc49375d84 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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