568

一个 64 位的 double 可以精确地表示整数 +/- 2 53

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

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

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

我试过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. 的答案是不可接受的,因为他们都任意四舍五入到小数点后两位。请在回答之前了解问题。


请注意,这String.format(format, args...)取决于语言环境(请参阅下面的答案)。

4

28 回答 28

442

如果想法是打印存储为双精度的整数,就好像它们是整数一样,否则以最小必要精度打印双精度:

public static String fmt(double d)
{
    if(d == (long) d)
        return String.format("%d",(long)d);
    else
        return String.format("%s",d);
}

产生:

232
0.18
1237875192
4.58
0
1.2345

并且不依赖于字符串操作。

于 2013-01-02T17:52:01.780 回答
241
String.format("%.2f", value);
于 2009-08-14T04:52:45.140 回答
119

简而言之:

如果您想摆脱尾随零和语言环境问题,那么您应该使用:

double myValue = 0.00000021d;

DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
df.setMaximumFractionDigits(340); //340 = DecimalFormat.DOUBLE_FRACTION_DIGITS

System.out.println(df.format(myValue)); //output: 0.00000021

解释:

为什么其他答案不适合我:

  • Double.toString()System.out.printlnorFloatingDecimal.toJavaFormatString如果 double 小于 10^-3 或大于或等于 10^7,则使用科学记数法

     double myValue = 0.00000021d;
     String.format("%s", myvalue); //output: 2.1E-7
    
  • 通过使用%f,默认小数精度为 6,否则您可以对其进行硬编码,但如果您的小数较少,则会导致添加额外的零。例子:

     double myValue = 0.00000021d;
     String.format("%.12f", myvalue); // Output: 0.000000210000
    
  • 通过使用setMaximumFractionDigits(0);%.0f删除任何小数精度,这对整数/长整数很好,但对双精度则不行

     double myValue = 0.00000021d;
     System.out.println(String.format("%.0f", myvalue)); // Output: 0
     DecimalFormat df = new DecimalFormat("0");
     System.out.println(df.format(myValue)); // Output: 0
    
  • 通过使用 DecimalFormat,您是本地依赖的。在法语语言环境中,小数点分隔符是逗号,而不是点:

     double myValue = 0.00000021d;
     DecimalFormat df = new DecimalFormat("0");
     df.setMaximumFractionDigits(340);
     System.out.println(df.format(myvalue)); // Output: 0,00000021
    

    使用 ENGLISH 语言环境可确保您得到一个小数点分隔符,无论您的程序将在何处运行。

为什么要使用 340setMaximumFractionDigits呢?

两个原因:

  • setMaximumFractionDigits接受整数,但其实现允许的最大位数DecimalFormat.DOUBLE_FRACTION_DIGITS等于 340
  • Double.MIN_VALUE = 4.9E-324因此,使用 340 位数字,您肯定不会舍入双精度数并丢失精度
于 2014-08-14T12:35:14.637 回答
39

采用:

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

这应该适用于 Double 支持的极值。它产生:

0.12
12
12.144252
0
于 2014-10-01T00:53:59.430 回答
31

在我的机器上,以下函数比JasonD 的 answer提供的函数快大约 7 倍,因为它避免了String.format

public static String prettyPrint(double d) {
  int i = (int) d;
  return d == i ? String.valueOf(i) : String.valueOf(d);
}
于 2014-02-09T22:11:06.720 回答
24

我的两分钱:

if(n % 1 == 0) {
    return String.format(Locale.US, "%.0f", n));
} else {
    return String.format(Locale.US, "%.1f", n));
}
于 2016-08-05T09:36:45.280 回答
15

呐,没关系。字符串操作导致的性能损失为零。

这是在后面修剪结尾的代码%f

private static String trimTrailingZeros(String number) {
    if(!number.contains(".")) {
        return number;
    }

    return number.replaceAll("\\.?0*$", "");
}
于 2009-03-31T23:03:55.147 回答
14
if (d == Math.floor(d)) {
    return String.format("%.0f", d); //Format is: 0 places after decimal point
} else {
    return Double.toString(d);
}

更多信息:https ://docs.oracle.com/javase/tutorial/java/data/numberformat.html

于 2016-07-29T10:33:07.163 回答
12
float price = 4.30;
DecimalFormat format = new DecimalFormat("0.##"); // Choose the number of decimal places to work with in case they are different than zero and zero value will be removed
format.setRoundingMode(RoundingMode.DOWN); // Choose your Rounding Mode
System.out.println(format.format(price));

这是一些测试的结果:

4.30     => 4.3
4.39     => 4.39  // Choose format.setRoundingMode(RoundingMode.UP) to get 4.4
4.000000 => 4
4        => 4
于 2019-12-09T14:22:16.303 回答
11

使用DecimalFormatsetMinimumFractionDigits(0)

于 2017-10-10T19:59:21.800 回答
10

这将很好地完成工作:

    public static String removeZero(double number) {
        DecimalFormat format = new DecimalFormat("#.###########");
        return format.format(number);
    }
于 2016-09-10T07:09:56.800 回答
7
new DecimalFormat("00.#").format(20.236)
//out =20.2

new DecimalFormat("00.#").format(2.236)
//out =02.2
  1. 0 表示最小位数
  2. 渲染 # 位数
于 2017-07-14T08:29:47.187 回答
6

请注意,这String.format(format, args...)取决于语言环境,因为它使用用户的默认语言环境进行格式化,也就是说,可能在123 456,789123,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...)不同国家的做法。

编辑好的,因为已经讨论过手续:

    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;
}
于 2015-03-13T10:24:52.980 回答
5

我做了一个DoubleFormatter有效地将大量双精度值转换为漂亮/可呈现的字符串:

double horribleNumber = 3598945.141658554548844;
DoubleFormatter df = new DoubleFormatter(4, 6); // 4 = MaxInteger, 6 = MaxDecimal
String beautyDisplay = df.format(horribleNumber);
  • 如果 V 的整数部分大于 MaxInteger => 以科学格式 (1.2345E+30) 显示 V。否则,以正常格式 (124.45678) 显示。
  • MaxDecimal 决定小数位数(用银行家四舍五入修剪)

这里的代码:

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;

/**
 * Convert a double to a beautiful String (US-local):
 *
 * double horribleNumber = 3598945.141658554548844;
 * DoubleFormatter df = new DoubleFormatter(4,6);
 * String beautyDisplay = df.format(horribleNumber);
 * String beautyLabel = df.formatHtml(horribleNumber);
 *
 * Manipulate 3 instances of NumberFormat to efficiently format a great number of double values.
 * (avoid to create an object NumberFormat each call of format()).
 *
 * 3 instances of NumberFormat will be reused to format a value v:
 *
 * if v < EXP_DOWN, uses nfBelow
 * if EXP_DOWN <= v <= EXP_UP, uses nfNormal
 * if EXP_UP < v, uses nfAbove
 *
 * nfBelow, nfNormal and nfAbove will be generated base on the precision_ parameter.
 *
 * @author: DUONG Phu-Hiep
 */
public class DoubleFormatter
{
    private static final double EXP_DOWN = 1.e-3;
    private double EXP_UP; // always = 10^maxInteger
    private int maxInteger_;
    private int maxFraction_;
    private NumberFormat nfBelow_;
    private NumberFormat nfNormal_;
    private NumberFormat nfAbove_;

    private enum NumberFormatKind {Below, Normal, Above}

    public DoubleFormatter(int maxInteger, int maxFraction){
        setPrecision(maxInteger, maxFraction);
    }

    public void setPrecision(int maxInteger, int maxFraction){
        Preconditions.checkArgument(maxFraction>=0);
        Preconditions.checkArgument(maxInteger>0 && maxInteger<17);

        if (maxFraction == maxFraction_ && maxInteger_ == maxInteger) {
            return;
        }

        maxFraction_ = maxFraction;
        maxInteger_ = maxInteger;
        EXP_UP =  Math.pow(10, maxInteger);
        nfBelow_ = createNumberFormat(NumberFormatKind.Below);
        nfNormal_ = createNumberFormat(NumberFormatKind.Normal);
        nfAbove_ = createNumberFormat(NumberFormatKind.Above);
    }

    private NumberFormat createNumberFormat(NumberFormatKind kind) {

        // If you do not use the Guava library, replace it with createSharp(precision);
        final String sharpByPrecision = Strings.repeat("#", maxFraction_);

        NumberFormat f = NumberFormat.getInstance(Locale.US);

        // Apply bankers' rounding:  this is the rounding mode that
        // statistically minimizes cumulative error when applied
        // repeatedly over a sequence of calculations
        f.setRoundingMode(RoundingMode.HALF_EVEN);

        if (f instanceof DecimalFormat) {
            DecimalFormat df = (DecimalFormat) f;
            DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();

            // Set group separator to space instead of comma

            //dfs.setGroupingSeparator(' ');

            // Set Exponent symbol to minus 'e' instead of 'E'
            if (kind == NumberFormatKind.Above) {
                dfs.setExponentSeparator("e+"); //force to display the positive sign in the exponent part
            } else {
                dfs.setExponentSeparator("e");
            }

            df.setDecimalFormatSymbols(dfs);

            // Use exponent format if v is outside of [EXP_DOWN,EXP_UP]

            if (kind == NumberFormatKind.Normal) {
                if (maxFraction_ == 0) {
                    df.applyPattern("#,##0");
                } else {
                    df.applyPattern("#,##0."+sharpByPrecision);
                }
            } else {
                if (maxFraction_ == 0) {
                    df.applyPattern("0E0");
                } else {
                    df.applyPattern("0."+sharpByPrecision+"E0");
                }
            }
        }
        return f;
    }

    public String format(double v) {
        if (Double.isNaN(v)) {
            return "-";
        }
        if (v==0) {
            return "0";
        }
        final double absv = Math.abs(v);

        if (absv<EXP_DOWN) {
            return nfBelow_.format(v);
        }

        if (absv>EXP_UP) {
            return nfAbove_.format(v);
        }

        return nfNormal_.format(v);
    }

    /**
     * Format and higlight the important part (integer part & exponent part)
     */
    public String formatHtml(double v) {
        if (Double.isNaN(v)) {
            return "-";
        }
        return htmlize(format(v));
    }

    /**
     * This is the base alogrithm: create a instance of NumberFormat for the value, then format it. It should
     * not be used to format a great numbers of value
     *
     * We will never use this methode, it is here only to understanding the Algo principal:
     *
     * format v to string. precision_ is numbers of digits after decimal.
     * if EXP_DOWN <= abs(v) <= EXP_UP, display the normal format: 124.45678
     * otherwise display scientist format with: 1.2345e+30
     *
     * pre-condition: precision >= 1
     */
    @Deprecated
    public String formatInefficient(double v) {

        // If you do not use Guava library, replace with createSharp(precision);
        final String sharpByPrecision = Strings.repeat("#", maxFraction_);

        final double absv = Math.abs(v);

        NumberFormat f = NumberFormat.getInstance(Locale.US);

        // Apply bankers' rounding:  this is the rounding mode that
        // statistically minimizes cumulative error when applied
        // repeatedly over a sequence of calculations
        f.setRoundingMode(RoundingMode.HALF_EVEN);

        if (f instanceof DecimalFormat) {
            DecimalFormat df = (DecimalFormat) f;
            DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();

            // Set group separator to space instead of comma

            dfs.setGroupingSeparator(' ');

            // Set Exponent symbol to minus 'e' instead of 'E'

            if (absv>EXP_UP) {
                dfs.setExponentSeparator("e+"); //force to display the positive sign in the exponent part
            } else {
                dfs.setExponentSeparator("e");
            }
            df.setDecimalFormatSymbols(dfs);

            //use exponent format if v is out side of [EXP_DOWN,EXP_UP]

            if (absv<EXP_DOWN || absv>EXP_UP) {
                df.applyPattern("0."+sharpByPrecision+"E0");
            } else {
                df.applyPattern("#,##0."+sharpByPrecision);
            }
        }
        return f.format(v);
    }

    /**
     * Convert "3.1416e+12" to "<b>3</b>.1416e<b>+12</b>"
     * It is a html format of a number which highlight the integer and exponent part
     */
    private static String htmlize(String s) {
        StringBuilder resu = new StringBuilder("<b>");
        int p1 = s.indexOf('.');

        if (p1>0) {
            resu.append(s.substring(0, p1));
            resu.append("</b>");
        } else {
            p1 = 0;
        }

        int p2 = s.lastIndexOf('e');
        if (p2>0) {
            resu.append(s.substring(p1, p2));
            resu.append("<b>");
            resu.append(s.substring(p2, s.length()));
            resu.append("</b>");
        } else {
            resu.append(s.substring(p1, s.length()));
            if (p1==0){
                resu.append("</b>");
            }
        }
        return resu.toString();
    }
}

注意:我使用了Guava库中的两个函数。如果您不使用 Guava,请自行编写代码:

/**
 * Equivalent to Strings.repeat("#", n) of the Guava library:
 */
private static String createSharp(int n) {
    StringBuilder sb = new StringBuilder();
    for (int i=0; i<n; i++) {
        sb.append('#');
    }
    return sb.toString();
}
于 2012-11-26T20:55:40.380 回答
4
String s = String.valueof("your int variable");
while (g.endsWith("0") && g.contains(".")) {
    g = g.substring(0, g.length() - 1);
    if (g.endsWith("."))
    {
        g = g.substring(0, g.length() - 1);
    }
}
于 2013-01-11T06:33:14.600 回答
4

您说您选择使用double 类型存储您的号码。我认为这可能是问题的根源,因为它迫使您将整数存储为双精度数(因此丢失了有关值性质的初始信息)。将您的数字存储在Number类(Double 和 Integer 的超类)的实例中并依靠多态性来确定每个数字的正确格式怎么样?

我知道因此重构代码的整个部分可能是不可接受的,但它可以在没有额外代码/转换/解析的情况下产生所需的输出。

例子:

import java.util.ArrayList;
import java.util.List;

public class UseMixedNumbers {

    public static void main(String[] args) {
        List<Number> listNumbers = new ArrayList<Number>();

        listNumbers.add(232);
        listNumbers.add(0.18);
        listNumbers.add(1237875192);
        listNumbers.add(4.58);
        listNumbers.add(0);
        listNumbers.add(1.2345);

        for (Number number : listNumbers) {
            System.out.println(number);
        }
    }

}

将产生以下输出:

232
0.18
1237875192
4.58
0
1.2345
于 2015-04-23T06:59:50.130 回答
2

这就是我想出的:

  private static String format(final double dbl) {
    return dbl % 1 != 0 ? String.valueOf(dbl) : String.valueOf((int) dbl);
  }

它是一个简单的单行代码,只有在确实需要时才转换为 int。

于 2018-04-11T17:45:13.983 回答
2

使用分组、舍入和没有不必要的零(双精度)格式化价格。

规则:

  1. 末尾没有零 ( 2.0000 = 2; 1.0100000 = 1.01)
  2. 点后最多两位数 ( 2.010 = 2.01; 0.20 = 0.2)
  3. 点后第 2 位四舍五入 ( 1.994 = 1.99; 1.995 = 2; 1.006 = 1.01; 0.0006 -> 0)
  4. 返回0( null/-0 = 0)
  5. 添加$( = $56/-$56)
  6. 分组 ( 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

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

于 2019-09-11T11:34:06.267 回答
2

对于 Kotlin,您可以使用如下扩展:

fun Double.toPrettyString() =
    if(this - this.toLong() == 0.0)
        String.format("%d", this.toLong())
    else
        String.format("%s", this)
于 2019-12-05T10:14:27.067 回答
1

这是另一个答案,它可以选择仅在十进制不为零时才附加十进制。

   /**
     * 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
    }
于 2020-05-14T15:07:35.187 回答
1

考虑到语言环境的简单解决方案:

double d = 123.45;
NumberFormat numberFormat = NumberFormat.getInstance(Locale.GERMANY);
System.out.println(numberFormat.format(d));

由于在德国使用逗号作为小数分隔符,上面将打印:

123,45

于 2021-09-06T15:45:53.067 回答
0

这里有两种方法来实现它。首先,更短(可能更好)的方式:

public static String formatFloatToString(final float f)
{
  final int i = (int)f;
  if(f == i)
    return Integer.toString(i);
  return Float.toString(f);
}

这是更长且可能更糟糕的方式:

public static String formatFloatToString(final float f)
{
  final String s = Float.toString(f);
  int dotPos = -1;
  for(int i=0; i<s.length(); ++i)
    if(s.charAt(i) == '.')
    {
      dotPos = i;
      break;
    }

  if(dotPos == -1)
    return s;

  int end = dotPos;
  for(int i = dotPos + 1; i<s.length(); ++i)
  {
    final char c = s.charAt(i);
    if(c != '0')
      end = i + 1;
  }
  final String result = s.substring(0, end);
  return result;
}
于 2013-05-18T23:03:38.007 回答
0
public static String fmt(double d) {
    String val = Double.toString(d);
    String[] valArray = val.split("\\.");
    long valLong = 0;
    if(valArray.length == 2) {
        valLong = Long.parseLong(valArray[1]);
    }
     if (valLong == 0)
        return String.format("%d", (long) d);
    else
        return String.format("%s", d);
}

我不得不使用它,因为d == (long)dSonarQube报告中给了我违规行为。

于 2017-07-25T11:45:23.903 回答
0

我在我们的JSF应用程序中使用它来格式化数字而不用尾随零。原始的内置格式化程序要求您指定最大小数位数,这在您有太多小数位数的情况下也很有用。

/**
 * Formats the given Number as with as many fractional digits as precision
 * available.<br>
 * This is a convenient method in case all fractional digits shall be
 * rendered and no custom format / pattern needs to be provided.<br>
 * <br>
 * This serves as a workaround for {@link NumberFormat#getNumberInstance()}
 * which by default only renders up to three fractional digits.
 *
 * @param number
 * @param locale
 * @param groupingUsed <code>true</code> if grouping shall be used
 *
 * @return
 */
public static String formatNumberFraction(final Number number, final Locale locale, final boolean groupingUsed)
{
    if (number == null)
        return null;

    final BigDecimal bDNumber = MathUtils.getBigDecimal(number);

    final NumberFormat numberFormat = NumberFormat.getNumberInstance(locale);
    numberFormat.setMaximumFractionDigits(Math.max(0, bDNumber.scale()));
    numberFormat.setGroupingUsed(groupingUsed);

    // Convert back for locale percent formatter
    return numberFormat.format(bDNumber);
}

/**
 * Formats the given Number as percent with as many fractional digits as
 * precision available.<br>
 * This is a convenient method in case all fractional digits shall be
 * rendered and no custom format / pattern needs to be provided.<br>
 * <br>
 * This serves as a workaround for {@link NumberFormat#getPercentInstance()}
 * which does not renders fractional digits.
 *
 * @param number Number in range of [0-1]
 * @param locale
 *
 * @return
 */
public static String formatPercentFraction(final Number number, final Locale locale)
{
    if (number == null)
        return null;

    final BigDecimal bDNumber = MathUtils.getBigDecimal(number).multiply(new BigDecimal(100));

    final NumberFormat percentScaleFormat = NumberFormat.getPercentInstance(locale);
    percentScaleFormat.setMaximumFractionDigits(Math.max(0, bDNumber.scale() - 2));

    final BigDecimal bDNumberPercent = bDNumber.multiply(new BigDecimal(0.01));

    // Convert back for locale percent formatter
    final String strPercent = percentScaleFormat.format(bDNumberPercent);

    return strPercent;
}
于 2020-10-26T16:35:19.137 回答
0

使用给定的十进制长度...

public static String getLocaleFloatValueDecimalWithLength(Locale loc, float value, int length) {
        //make string from float value
        return String.format(loc, (value % 1 == 0 ? "%.0f" : "%."+length+"f"), value);
    }
于 2022-02-15T21:57:31.673 回答
-1

这是一个实际有效的答案(此处结合不同的答案)

public static String removeTrailingZeros(double f)
{
    if(f == (int)f) {
        return String.format("%d", (int)f);
    }
    return String.format("%f", f).replaceAll("0*$", "");
}
于 2013-05-23T18:41:32.950 回答
-4

最好的方法如下:

public class Test {

    public static void main(String args[]){
        System.out.println(String.format("%s something", new Double(3.456)));
        System.out.println(String.format("%s something", new Double(3.456234523452)));
        System.out.println(String.format("%s something", new Double(3.45)));
        System.out.println(String.format("%s something", new Double(3)));
    }
}

输出:

3.456 something
3.456234523452 something
3.45 something
3.0 something

唯一的问题是最后一个没有删除 .0 的问题。但是,如果您能够忍受这种情况,那么这种方法效果最好。%.2f 会将其四舍五入到最后两位小数。DecimalFormat 也是如此。如果您需要所有小数位,但不需要尾随零,那么这效果最好。

于 2012-05-09T09:04:15.873 回答
-10
String s = "1.210000";
while (s.endsWith("0")){
    s = (s.substring(0, s.length() - 1));
}

这将使字符串丢弃拖尾 0-s。

于 2011-10-26T12:39:25.663 回答