Mëd*_* KB 0 android android-studio
我想将以下数字格式化为Android旁边的数字:
1000至1k 5821至5.8k 2000000至2m 7800000至7.8m
Ket*_*ani 12
功能
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);
}
}
Run Code Online (Sandbox Code Playgroud)
用
prettyCount(789); Output: 789
prettyCount(5821); Output: 5.8k
prettyCount(101808); Output: 101.8k
prettyCount(7898562); Output: 7.9M
Run Code Online (Sandbox Code Playgroud)
Sta*_*wer 10
这应该可以解决问题
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();
}
Run Code Online (Sandbox Code Playgroud)
Gui*_*sta 10
从 Android 7.0 (API 24) 开始,可以使用CompactDecimalFormat.
例如 :
private String convertNumber(int number, Locale locale) {
CompactDecimalFormat compactDecimalFormat =
CompactDecimalFormat.getInstance(locale, CompactDecimalFormat.CompactStyle.SHORT);
return compactDecimalFormat.format(number);
}
Run Code Online (Sandbox Code Playgroud)
此类也是 ICU v49 的一部分 ( https://unicode-org.github.io/icu-docs/apidoc/dev/icu4j/com/ibm/icu/text/CompactDecimalFormat.html )。
此外,从 Android 11 (API 30) 开始,可以使用NumberFormatter.
该类也是 ICU v60 的一部分。
小智 9
试试这个方法:
对于 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));
}
Run Code Online (Sandbox Code Playgroud)
对于 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])
}
Run Code Online (Sandbox Code Playgroud)
试试这个技巧:
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));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2179 次 |
| 最近记录: |