问题
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
回答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();
}
回答2:
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));
}
回答3:
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
回答4:
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])
}
来源:https://stackoverflow.com/questions/41859525/how-to-go-about-formatting-1200-to-1-2k-in-android-studio