64位double可以精确地表示整数+/- 253。

鉴于这一事实,我选择使用双类型作为我所有类型的单一类型,因为我的最大整数是一个无符号的32位数字。

但现在我必须打印这些伪整数,但问题是它们也和实际的双精度数混合在一起。

那么如何在Java中很好地打印这些double呢?

我试过String。format("%f", value),这很接近,除了我得到了很多小值的末尾零。

下面是%f的输出示例

232.00000000
0.18000000000
1237875192.0
4.5800000000
0.00000000
1.23450000

我想要的是:

232
0.18
1237875192
4.58
0
1.2345

当然,我可以写一个函数来修剪这些零,但由于字符串操作,这是大量的性能损失。我能用其他格式的代码做得更好吗?


Tom E.和Jeremy S.的答案是不可接受的,因为他们都任意舍入到小数点后两位。请先理解问题再回答。


请注意字符串。Format (Format, args…)依赖于语言环境(见下面的答案)。


当前回答

请注意字符串。Format (Format, args…)依赖于语言环境,因为它使用用户的默认语言环境进行格式化,也就是说,可能在其中使用逗号甚至空格,如123 456,789或123,456.789,这可能不是您所期望的。

你可能更喜欢使用String.format((Locale)null, format, args…)

例如,

    double f = 123456.789d;
    System.out.println(String.format(Locale.FRANCE,"%f",f));
    System.out.println(String.format(Locale.GERMANY,"%f",f));
    System.out.println(String.format(Locale.US,"%f",f));

打印

123456,789000
123456,789000
123456.789000

这就是String的内容。Format (Format, args…)

EDIT好的,既然已经讨论了有关手续的问题:

    res += stripFpZeroes(String.format((Locale) null, (nDigits!=0 ? "%."+nDigits+"f" : "%f"), value));
    ...

protected static String stripFpZeroes(String fpnumber) {
    int n = fpnumber.indexOf('.');
    if (n == -1) {
        return fpnumber;
    }
    if (n < 2) {
        n = 2;
    }
    String s = fpnumber;
    while (s.length() > n && s.endsWith("0")) {
        s = s.substring(0, s.length()-1);
    }
    return s;
}

其他回答

Use:

if (d % 1.0 != 0)
    return String.format("%s", d);
else
    return String.format("%.0f", d);

这应该与Double支持的极值一起工作。它的收益率:

0.12
12
12.144252
0

这是另一个答案,它有一个选项,只有当小数不为零时才附加小数。

   /**
     * Example: (isDecimalRequired = true)
     * d = 12345
     * returns 12,345.00
     *
     * d = 12345.12345
     * returns 12,345.12
     *
     * ==================================================
     * Example: (isDecimalRequired = false)
     * d = 12345
     * returns 12,345 (notice that there's no decimal since it's zero)
     *
     * d = 12345.12345
     * returns 12,345.12
     *
     * @param d float to format
     * @param zeroCount number decimal places
     * @param isDecimalRequired true if it will put decimal even zero,
     * false will remove the last decimal(s) if zero.
     */
    fun formatDecimal(d: Float? = 0f, zeroCount: Int, isDecimalRequired: Boolean = true): String {
        val zeros = StringBuilder()

        for (i in 0 until zeroCount) {
            zeros.append("0")
        }

        var pattern = "#,##0"

        if (zeros.isNotEmpty()) {
            pattern += ".$zeros"
        }

        val numberFormat = DecimalFormat(pattern)

        var formattedNumber = if (d != null) numberFormat.format(d) else "0"

        if (!isDecimalRequired) {
            for (i in formattedNumber.length downTo formattedNumber.length - zeroCount) {
                val number = formattedNumber[i - 1]

                if (number == '0' || number == '.') {
                    formattedNumber = formattedNumber.substring(0, formattedNumber.length - 1)
                } else {
                    break
                }
            }
        }

        return formattedNumber
    }

0.0 -> 0% 1.0 -> 100% 0.1 -> 10% 0.11 -> 11% 0.01 -> 1% 0.111 -> 11.1% 0.001 -> 0.1% 0.1111 -> 11.11% 0.0001 -> 0.01%

添加".replace()"是因为我总是使用错误的分隔符

import java.text.NumberFormat

fun Double.formating(): String {
    val defaultFormat: NumberFormat = NumberFormat.getPercentInstance()
    defaultFormat.minimumFractionDigits = 0
    defaultFormat.maximumFractionDigits = 2

    return defaultFormat.format(this).replace(",", ".")
}
String.format("%.2f", value);

用分组、四舍五入和没有不必要的零(双位数)格式化价格。

规则:

末尾没有零(2.0000 = 2;1.0100000 = 1.01) 一个点后最多两位数(2.010 = 2.01;0.20 = 0.2) 一个点后的第二位数字(1.994 = 1.99;1.995 = 2;1.006 = 1.01;0.0006 -> 0 返回0 (null/-0 = 0) 增加$ (= $56/-$56) 分组(101101.02 = $101,101.02)

更多的例子:

-99.985 = -$99.99 10 = $10 10.00 = $10 20.01000089 = $20.01

它是用Kotlin编写的,作为Double的一个有趣的扩展(因为它在Android中使用),但它可以很容易地转换为Java,因为使用了Java类。

/**
 * 23.0 -> $23
 *
 * 23.1 -> $23.1
 *
 * 23.01 -> $23.01
 *
 * 23.99 -> $23.99
 *
 * 23.999 -> $24
 *
 * -0.0 -> $0
 *
 * -5.00 -> -$5
 *
 * -5.019 -> -$5.02
 */
fun Double?.formatUserAsSum(): String {
    return when {
        this == null || this == 0.0 -> "$0"
        this % 1 == 0.0 -> DecimalFormat("$#,##0;-$#,##0").format(this)
        else -> DecimalFormat("$#,##0.##;-$#,##0.##").format(this)
    }
}

使用方法:

var yourDouble: Double? = -20.00
println(yourDouble.formatUserAsSum()) // will print -$20

yourDouble = null
println(yourDouble.formatUserAsSum()) // will print $0

关于DecimalFormat: https://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html