The following snippet returns the shorthand of the given value.
Examples:
shorthand(1234567, 0, false);
12M
shorthand(1234567, 2, false);
12.35M
shorthand(1234567, 2, true);
12.34M
shorthand(1234567, 3, false);
12.346M
shorthand(1234567, 3, true);
12.345M
/**
* Returns the shorthand of <code>number</code> rounded to <code>precision</code> significant figures.
* <pre> Metric prefixes
* Symbol Factor
* k 10^3
* M 10^6
* G 10^9
* T 10^12
* P 10^15
* E 10^18
* Z 10^21
* Y 10^24</pre>
* <p><i>Note: A precision of 2 is used by default if necessary</i></p>
*
* @param number the number to get the shorthand of
* @param precision the significant figures
* @param keepAccuracy <tt>true</tt> to keep accuracy; otherwise <tt>false</tt>
* @return the shorthand of <code>number</code> rounded to <code>precision</code> significant figures
*/
public String shorthand(long number, int precision, boolean keepAccuracy) {
String sign = number < 0 ? "-" : "";
number = Math.abs(number);
if (number < 1000) {
return sign + number;
} else if (precision < 0) {
precision = 2;
}
int exponent = (int) (Math.log(number) / Math.log(1000));
char suffix = "kMGTPEZY".charAt(exponent - 1);
double significand = number / Math.pow(1000, exponent);
if (!keepAccuracy) {
return sign + String.format("%." + precision + "f%s", significand, suffix);
} else {
String result = String.valueOf(significand);
if (precision == 0) {
return sign + result.substring(0, result.indexOf(".")) + suffix;
}
int length = result.substring(result.indexOf(".") + 1).length();
if (precision > length) {
precision = 2;
}
return sign + result.substring(0, result.length() - (length - precision)) + suffix;
}
}