Created
July 8, 2015 12:02
-
-
Save shayousefi/daded32583685f385129 to your computer and use it in GitHub Desktop.
Formatting a number count to an abbreviated form with the appropriate unit suffix.
This file contains 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
/** | |
* Formats a number count to an abbreviated form with the appropriate unit suffix. | |
* | |
* @param count number count | |
* @param <T> type of number | |
* @return An abbreviated count with the appropriate unit suffix. | |
*/ | |
public static <T extends Number & Comparable<? super T>> String shortCount(T count) { | |
String base = "##0"; | |
String[] suffixes = {"'K'", "'M'", "'B'"}; | |
BigDecimal decimalCount = new BigDecimal(count.toString()); | |
for (int i = suffixes.length - 1; i >= 0; i--) { | |
BigInteger truncCount = decimalCount.scaleByPowerOfTen(-3 * (i + 1)).toBigInteger(); | |
if (truncCount.compareTo(BigInteger.ZERO) > 0) { | |
return new DecimalFormat(base + suffixes[i]).format(truncCount); | |
} | |
} | |
return new DecimalFormat(base).format(count); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment