Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to go about formatting 1200 to 1.2k in Android studio

I'd like to format following numbers into the numbers next to them with Android:

1000 to 1k 5821 to 5.8k 2000000 to 2m 7800000 to 7.8m

like image 849
Mëd KB Avatar asked Jan 25 '17 19:01

Mëd KB


2 Answers

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
like image 184
Ketan Ramani Avatar answered Sep 22 '22 17:09

Ketan Ramani


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])
}
like image 22
Ashav Kothari Avatar answered Sep 23 '22 17:09

Ashav Kothari