如何很好地将浮动数字格式化为字符串而不必要的小数0?

Pyr*_*cal 472 java string format floating-point double

64位双精度可以精确地表示整数+/- 2 53

鉴于这一事实,我选择将double类型用作所有类型的单一类型,因为我的最大整数是无符号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.的答案是不可接受的,因为它们都可以任意舍入到小数点后两位.请在回答之前先了解问题.

编辑2

请注意,String.format(format, args...)区域设置相关的(见下面的答案).

Tom*_*rez 398

new DecimalFormat("#.##").format(1.199); //"1.2"
Run Code Online (Sandbox Code Playgroud)

正如评论中所指出的,这不是原始问题的正确答案.
也就是说,这是一种非常有用的格式化数字的方法,没有不必要的尾随零.

  • 如果您碰巧想要特定数量的尾随零(例如,如果您正在打印金额),那么您可以使用'0'而不是'#'(即新的DecimalFormat("0.00").格式(金额);)这个不是OP想要的,但可能对参考有用. (53认同)
  • 是的,作为问题的原始作者,这是错误的答案.有趣的是有多少票.这个解决方案的问题是它任意舍入到2位小数. (20认同)
  • 这里一个重要的注意事项是1.1将被正确地格式化为"1.1"而没有任何尾随零. (15认同)
  • @Pyrolistical - 恕我直言,有很多赞成票,因为虽然这对你来说是错误的解决方案,但对于那些发现这个问答的99%以上的人来说,这是正确的解决方案:通常,双人的最后几位是"噪音",使输出混乱,干扰可读性.因此,程序员确定有多少数字对阅读输出的人有益,并指定许多数字.常见的情况是累积了小的数学错误,因此值可能是12.000000034,但更喜欢舍入到12,并紧凑地显示为"12".并且"12.340000056"=>"12.34". (13认同)
  • @Mazyod因为你总是可以传入一个浮动的指针,其中包含比格式更多的小数.那就是编写大部分时间都能工作的代码,但不能覆盖所有边缘情况. (10认同)
  • @Pyrolistical我不明白为什么你不能只使用:`new DecimalFormat("#.##########").format(1.199);`??? (5认同)
  • @Pyrolistical你可以使用这么多的小数点,它不会超出由于内部浮点表示而丢失精度的格式(即在很多小数位,`double`失去精度).但是,这是一个尴尬的解决方案; 我相信JasonD的答案是最好的方式. (2认同)
  • 伙计,我欠你一杯啤酒:-) (2认同)

Jas*_*onD 377

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

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

生产:

232
0.18
1237875192
4.58
0
1.2345
Run Code Online (Sandbox Code Playgroud)

而且不依赖于字符串操作.

  • OP明确表示他们不想*使用`%f`格式化输出.答案是针对所描述的情况和所需的输出.OP建议他们的最大值是32位无符号整数,我认为`int`是可接受的(无符号实际上不存在于Java中,并且没有示例存在问题),但将`int`更改为`long`是如果情况不同,这是一个微不足道的修复. (24认同)
  • 对于大于max`int`的值不起作用. (20认同)
  • 问题是`%s`不能与Locales一起使用.在德语中,我们使用","而不是".".十进制数.当`String.format(Locale.GERMAN,"%f",1.5)`返回"1,500000"时,`String.format(Locale.GERMAN,"%s",1.5)`返回"1.5" - 带有" ",这在德语中是假的.是否还有依赖于语言环境的"%s"版本? (14认同)
  • 同意,这是一个糟糕的答案,不要使用它.它无法使用大于最大`int`值的`double`.即使是"长",它仍然会因大数而失败.此外,它将以指数形式返回一个String,例如"1.0E10",用于大值,这可能不是提问者想要的.在第二个格式字符串中使用`%f`而不是`%s`来修复它. (8认同)
  • `的String.format( "%S",d)`??? 谈论不必要的开销.使用`Double.toString(d)`.另一个相同:`Long.toString((long)d)`. (6认同)
  • 它以科学计数法格式化"0.00028571". (3认同)

Jer*_*ade 227

String.format("%.2f", value) ;
Run Code Online (Sandbox Code Playgroud)

  • 由于问题是要求删除所有尾随零,所以下来投票,这个答案将始终留下两个浮点,而不管是零. (78认同)
  • 这是正确的,但即使没有小数部分也总是打印尾随零.String.format("%.2f,1.0005)打印1.00而不是1.是否有任何格式说明符,如果它不存在,则不打印小数部分? (12认同)
  • 肯定有200多个积极的答案! (8认同)
  • 我真的不明白为什么这个答案被投票赞成):它与问题无关。 (5认同)
  • 我认为你可以通过使用g代替f来正确处理尾随零. (2认同)
  • 我在"%.5f"的生产系统中使用了这个解决方案,它真的非常糟糕,不要使用它...因为它打印了这个:5.12E-4而不是0.000512 (2认同)

JBE*_*JBE 83

简而言之:

如果你想摆脱尾随零和Locale问题,那么你应该使用:

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
Run Code Online (Sandbox Code Playgroud)

说明:

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

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

    double myValue = 0.00000021d;
    String.format("%s", myvalue); //output: 2.1E-7
    
    Run Code Online (Sandbox Code Playgroud)
  • 通过使用%f,默认的小数精度是6,否则你可以对它进行硬编码,但如果你的小数点少,它会导致额外的零.示例:

    double myValue = 0.00000021d;
    String.format("%.12f", myvalue); //output: 0.000000210000
    
    Run Code Online (Sandbox Code Playgroud)
  • 通过使用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
    
    Run Code Online (Sandbox Code Playgroud)
  • 通过使用DecimalFormat,您是本地依赖的.在法语区域设置中,小数点分隔符是逗号,而不是点:

    double myValue = 0.00000021d;
    DecimalFormat df = new DecimalFormat("0");
    df.setMaximumFractionDigits(340);
    System.out.println(df.format(myvalue));//output: 0,00000021
    
    Run Code Online (Sandbox Code Playgroud)

    使用ENGLISH语言环境可确保在程序运行的任何位置获得小数点分隔符

为什么使用340 setMaximumFractionDigits呢?

两个原因:

  • setMaximumFractionDigits接受一个整数,但其实现的最大允许位数DecimalFormat.DOUBLE_FRACTION_DIGITS等于340
  • Double.MIN_VALUE = 4.9E-324 因此,使用340位数字,您肯定不会绕过双倍和松散的精度

  • 谢谢!事实上,这个答案是唯一一个真正符合问题中提到的所有要求的答案 - 它没有显示不必要的零,不会对数字进行舍入并且与语言环境相关.大! (4认同)
  • 因为这个属性不是公开的……它是“包友好的” (3认同)

Val*_*loş 25

为什么不:

if (d % 1.0 != 0)
    return String.format("%s", d);
else
    return String.format("%.0f",d);
Run Code Online (Sandbox Code Playgroud)

这应该与Double支持的极值一起使用.产量:

0.12
12
12.144252
0
Run Code Online (Sandbox Code Playgroud)

  • 我更喜欢这个答案,我们不需要进行类型转换. (2认同)

Fer*_*ego 23

我的2美分:

if(n % 1 == 0) {
    return String.format(Locale.US, "%.0f", n));
} else {
    return String.format(Locale.US, "%.1f", n));
}
Run Code Online (Sandbox Code Playgroud)

  • 或者只是`return String.format(Locale.US,(n%1 == 0?"%.0f":"%.1f"),n);`. (2认同)
  • 当 23.00123 ==> 23.00 时失败 (2认同)
  • 你在干什么?它总是在点后四舍五入到 1 位,这不是问题的答案。为什么有些人不识字? (2认同)

Rok*_*iša 22

在我的机器上,以下功能大约比JasonD的答案提供的功能快7倍,因为它避免了String.format:

public static String prettyPrint(double d) {
  int i = (int) d;
  return d == i ? String.valueOf(i) : String.valueOf(d);
}
Run Code Online (Sandbox Code Playgroud)

  • 嗯,这不考虑语言环境,但 JasonD 也不考虑。 (2认同)

Pyr*_*cal 11

NOW,没关系.

字符串操作导致的性能损失为零.

以下是修改结束的代码 %f

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

    return number.replaceAll("\\.?0*$", "");
}
Run Code Online (Sandbox Code Playgroud)

  • 我贬低了,因为你的解决方案不是最好的方法.看看String.format.您需要在此实例中使用正确的格式类型float.看看我的上述答案. (7认同)
  • 我投了票,因为我遇到了同样的问题,这里似乎没有人理解这个问题. (5认同)
  • 对于上面,也许他想修剪零而不进行舍入?PS @Pyrolistical,你当然可以使用number.replaceAll(".?0*$",""); (当然包含(".")之后) (3认同)

小智 8

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));
Run Code Online (Sandbox Code Playgroud)

这是一些测试的结果:

4.30     => 4.3
4.39     => 4.39  // Choose format.setRoundingMode(RoundingMode.UP) to get 4.4
4.000000 => 4
4        => 4
Run Code Online (Sandbox Code Playgroud)

  • 唯一令我满意的解决方案 (2认同)

Hos*_*deh 7

new DecimalFormat("00.#").format(20.236)
//out =20.2

new DecimalFormat("00.#").format(2.236)
//out =02.2
Run Code Online (Sandbox Code Playgroud)
  1. 0 表示最小位数
  2. 呈现 # 位数字


vla*_*zle 7

使用DecimalFormatsetMinimumFractionDigits(0)


fop*_*316 6

if (d == Math.floor(d)) {
    return String.format("%.0f", d);
} else {
    return Double.toString(d);
}
Run Code Online (Sandbox Code Playgroud)


Hie*_*iep 5

我做了一个DoubleFormatter有效地将大量的double值转换为一个漂亮/可呈现的String:

double horribleNumber = 3598945.141658554548844; 
DoubleFormatter df = new DoubleFormatter(4,6); //4 = MaxInteger, 6 = MaxDecimal
String beautyDisplay = df.format(horribleNumber);
Run Code Online (Sandbox Code Playgroud)
  • 如果V的整数部分具有科学家格式(1.2345e + 30)以上的MaxInteger => display 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) {
        final String sharpByPrecision = Strings.repeat("#", maxFraction_); //if you do not use Guava library, replace with createSharp(precision);
        NumberFormat f = NumberFormat.getInstance(Locale.US);

        //Apply banker's 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 out side 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) {

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

        final double absv = Math.abs(v);

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

        //Apply banker's 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:我使用了GUAVA库中的2个函数.如果您不使用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();
}
Run Code Online (Sandbox Code Playgroud)


184*_*615 5

请注意,它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));
Run Code Online (Sandbox Code Playgroud)

版画

123456,789000
123456,789000
123456.789000
Run Code Online (Sandbox Code Playgroud)

这就是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;
}
Run Code Online (Sandbox Code Playgroud)


Bia*_*aly 5

这个我可以很好地完成工作,我知道这个话题很老,但是直到遇到这个问题我一直在努力解决同样的问题。我希望有人觉得它有用。

    public static String removeZero(double number) {
        DecimalFormat format = new DecimalFormat("#.###########");
        return format.format(number);
    }
Run Code Online (Sandbox Code Playgroud)