How to go about formatting 1200 to 1.2k in Android studio
Try this trick:
private String numberCalculation(long number) {
if (number < 1000)
return "" + number;
int exp = (int) (Math.log(number) / Math.log(1000));
return String.format("%.1f %c", number / Math.pow(1000, exp), "kMGTPE".charAt(exp-1));
}
This should do the trick
String numberString = "";
if (Math.abs(number / 1000000) > 1) {
numberString = (number / 1000000).toString() + "m";
} else if (Math.abs(number / 1000) > 1) {
numberString = (number / 1000).toString() + "k";
} else {
numberString = number.toString();
}
Try this method :
For Java
public static String formatNumber(long count) {
if (count < 1000) return "" + count;
int exp = (int) (Math.log(count) / Math.log(1000));
return String.format("%.1f %c", count / Math.pow(1000, exp),"kMGTPE".charAt(exp-1));
}
For Kotlin(Android)
fun getFormatedNumber(count: Long): String {
if (count < 1000) return "" + count
val exp = (ln(count.toDouble()) / ln(1000.0)).toInt()
return String.format("%.1f %c", count / 1000.0.pow(exp.toDouble()), "kMGTPE"[exp - 1])
}
Function
public String prettyCount(Number number) {
char[] suffix = {' ', 'k', 'M', 'B', 'T', 'P', 'E'};
long numValue = number.longValue();
int value = (int) Math.floor(Math.log10(numValue));
int base = value / 3;
if (value >= 3 && base < suffix.length) {
return new DecimalFormat("#0.0").format(numValue / Math.pow(10, base * 3)) + suffix[base];
} else {
return new DecimalFormat("#,##0").format(numValue);
}
}
Use
prettyCount(789); Output: 789
prettyCount(5821); Output: 5.8k
prettyCount(101808); Output: 101.8k
prettyCount(7898562); Output: 7.9M