android - 将酷格式转换为两位小数
问题描述
我正在使用以下方法以格式化方式转换数字,例如
private static String coolFormat(double n, int iteration) {
double d = ((long) n / 100) / 10.0;
boolean isRound = (d * 10) %10 == 0;//true if the decimal part is equal to 0 (then it's trimmed anyway)
return (d < 1000? //this determines the class, i.e. 'k', 'm' etc
((d > 99.9 || isRound || (!isRound && d > 9.99)? //this decides whether to trim the decimals
(int) d * 10 / 10 : d + "" // (int) d * 10 / 10 drops the decimal
) + "" + c[iteration])
: coolFormat(d, iteration+1));
}
如何得到两位小数的结果。
Log.e("PrintValue ", coolFormat(1520,0)+"");
06-01 15:57:07.625 19542-19542/? E/PrintValue: 1.5k
如果我输入 1520 OUTPUT=> 1.5k 但输出应该是 1.52k
解决方案
尝试以下方法,它应该适合你
public static String formatNumberExample(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.00").format(numValue / Math.pow(10, base * 3)) + suffix[base];
} else {
return new DecimalFormat("#,##0").format(numValue);
}
}
证明:
推荐阅读
- vuejs2 - 后端更新保存后对象数组内的Vuex突变
- java - 如何根据对象的属性在 Java 8 中求和
- google-apps-script - 如何在 Google Classroom CourseWork.list 调用中使用 DRAFT 枚举
- sublimetext3 - 用于打开键绑定和设置的崇高文本快捷方式
- java - Log4j:如何为 Logger 使用自定义名称?
- ionic-framework - ionic cordova build android 之间的区别
- android - 为什么我的 Android 单元测试一起运行时失败,但单独运行时通过?
- php - 如何在php中使用curl从twitter获取流数据
- python - 如何从 Django LogEntry 查询多个 content_type 模型?
- c# - 如果类接受许多参数,那么创建不可变类的最简洁方法是什么?