将冷格式转换为两个小数点

时间:2018-06-01 10:21:18

标签: android numbers format

我使用以下方法以格式化方式转换数字,如

 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 =&gt; 1.5k但输出应为1.52k

1 个答案:

答案 0 :(得分:1)

尝试以下适合您的方法

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);
    }
}

证明:

image_proof