如何将浮点数很好地格式化为String而没有不必要的十进制0?

64位双精度数可以精确表示整数+/- 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

当然,我可以编写一个函数来修剪这些零,但是由于String操作,这会导致很多性能损失。 我可以使用其他格式代码做得更好吗?

编辑

Tom E.和Jeremy S.的答案都是不可接受的,因为它们都四舍五入到小数点后两位。 请在回答之前了解问题。

编辑2

请注意, String.format(format, args...)是与语言环境相关的 (请参见下面的答案)。


#1楼

我知道这是一个非常老的线程。但是我认为做到这一点的最佳方法如下:

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会将其四舍五入到最后2个十进制数字。 因此,DecimalFormat。 如果您需要所有小数位而不是尾随零,那么这是最好的。


#2楼

String.format("%.2f", value) ;

#3楼

我制作了DoubleFormatter以将大量的双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) {
        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();
    }
}

注意:我使用了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();
}

#4楼

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

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

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


#5楼

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

#6楼

这是实现它的两种方法。 首先,较短(可能更好)的方法是:

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

#7楼

这是一个实际可行的答案(此处结合了不同的答案)

public static String removeTrailingZeros(double f)
{
    if(f == (int)f) {
        return String.format("%d", (int)f);
    }
    return String.format("%f", f).replaceAll("0*$", "");
}

#8楼

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

public static String prettyPrint(double d) {
  int i = (int) d;
  return d == i ? String.valueOf(i) : String.valueOf(d);
}

#9楼

简而言之:

如果要摆脱尾随零和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

说明:

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

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

     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 

    使用英语语言环境可确保在程序运行的任何地方都获得小数点

为什么要对setMaximumFractionDigits使用340?

两个原因:

  • setMaximumFractionDigits接受一个整数,但是其实现具有允许的最大数字DecimalFormat.DOUBLE_FRACTION_DIGITS等于340
  • Double.MIN_VALUE = 4.9E-324所以使用340位数字时,请确保不要舍入双精度和宽松精度

#10楼

为什么不:

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

这应该可以使用Double支持的极限值。 产量:

0.12
12
12.144252
0

#11楼

请注意, 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...)在不同国家/地区的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;
}

#12楼

答案迟了,但是...

您说您选择使用双精度类型存储数字。 我认为这可能是问题的根源,因为它迫使您将整数存储为双精度型(因此丢失了有关值性质的初始信息)。 将数字存储在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

#13楼

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

#14楼

我的2美分:

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

#15楼

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

    public static String removeZero(double number) {
        DecimalFormat format = new DecimalFormat("#.###########");
        return format.format(number);
    }

#16楼

new DecimalFormat("#.##").format(1.199); //"1.2"

正如评论中指出的那样,这不是对原始问题的正确答案。
也就是说,这是一种非常有用的数字格式,无需多余的尾随零。


#17楼

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

new DecimalFormat("00.#").format(2.236)
//out =02.2
  1. 0为最小位数
  2. 渲染数字

#18楼

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)d在声纳报告中给了我违反


#19楼

使用DecimalFormatsetMinimumFractionDigits(0)


#20楼

这是我想出的:

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

简单的一个内衬,仅在确实需要时才强制转换为int


#21楼

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

规则:

  1. 末尾没有零( 2.0000 = 2; 1.0100000 = 1.01
  2. 点后最多两位数( 2.010 = 2.01; 0.20 = 0.2
  3. 在一个点后的第二个数字后舍入( 1.994 = 1.99; 1.995 = 2; 1.006 = 1.01; 0.0006 -> 0
  4. 返回0null/-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


#22楼

这可能很明显,但有时注释会有所帮助。 如果不想更改浮位数,则可以使用println

System.out.println("YOUR STRING" + YOUR_DOUBLE_VARIABLE);

#23楼

w,没关系。

由于字符串操作而导致的性能损失为零。

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

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

    return number.replaceAll("\\.?0*$", "");
}

#24楼

String s = "1.210000";
while (s.endsWith("0")){
    s = (s.substring(0, s.length() - 1));
}

这将使字符串的尾部下降0-s。

发布了0 篇原创文章 · 获赞 2 · 访问量 5917

猜你喜欢

转载自blog.csdn.net/asdfgh0077/article/details/104068267
今日推荐