Skip to content

Instantly share code, notes, and snippets.

@shayousefi
Created July 8, 2015 12:02
Show Gist options
  • Save shayousefi/daded32583685f385129 to your computer and use it in GitHub Desktop.
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.
/**
* 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