Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/373.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何很好地将浮点数格式化为字符串,而不需要不必要的十进制0';s_Java_String_Floating Point_Format_Double - Fatal编程技术网

Java 如何很好地将浮点数格式化为字符串,而不需要不必要的十进制0';s

Java 如何很好地将浮点数格式化为字符串,而不需要不必要的十进制0';s,java,string,floating-point,format,double,Java,String,Floating Point,Format,Double,64位双精度可以精确表示整数+/-253 鉴于这一事实,我选择使用双精度类型作为所有类型的单一类型,因为我的最大整数是一个无符号32位数字 但现在我必须打印这些伪整数,但问题是它们也与实际的双精度数混合在一起 那么如何在Java中很好地打印这些双精度 我已经尝试了String.format(“%f”,value),这很接近,只是我得到了很多小值的尾随零 下面是of%f 232.00000000 0.18000000000 1237875192.0 4.5800000000 0.00000000

64位双精度可以精确表示整数+/-253

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

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

那么如何在Java中很好地打印这些双精度

我已经尝试了
String.format(“%f”,value)
,这很接近,只是我得到了很多小值的尾随零

下面是of
%f

232.00000000 0.18000000000 1237875192.0 4.5800000000 0.00000000 1.23450000 232 0.18000000000 1237875192 4.5800000000 0 1.23450000 我想要的是:

232 0.18 1237875192 4.58 0 1.2345 232 0.18 1237875192 4.58 0 1.2345 当然,我可以编写一个函数来修剪这些零,但由于字符串操作,这会造成很多性能损失。我能用其他格式代码做得更好吗


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



请注意,
String.format(format,args…
取决于地区设置(请参见下面的答案)。

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

下面是在
%f
之后修剪末端的代码:

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

    return number.replaceAll("\\.?0*$", "");
}
正如评论中所指出的,这不是对原始问题的正确答案。
这就是说,这是一种非常有用的方法,可以格式化数字,而不需要不必要的尾随零

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

这将使字符串以0-s的速度落下尾部。

最好的方法如下:

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什么的
3.45623452什么的
3.45什么
3.0什么的

唯一的问题是最后一个没有删除.0的问题。但如果你能接受这一点,那么这是最好的。2f将其四舍五入到最后两位小数。决策格式也是如此。如果您需要所有的小数位,但不需要尾随的零,那么这是最好的方法。

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

double horribleNumber = 3598945.141658554548844;
DoubleFormatter df = new DoubleFormatter(4, 6); // 4 = MaxInteger, 6 = MaxDecimal
String beautyDisplay = df.format(horribleNumber);
  • 如果V的整数部分大于MaxInteger=>以科学格式显示V(1.2345E+30)。否则,以正常格式显示(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();
    }
}
import java.math.RoundingMode;
导入java.text.DecimalFormat;
导入java.text.DecimalFormatSymbols;
导入java.text.NumberFormat;
导入java.util.Locale;
导入com.google.common.base.premissions;
导入com.google.common.base.Strings;
/**
*将双精度转换为漂亮的字符串(美国本地):
*
*双倍数字=3598945.1416585548844;
*双格式化程序df=新的双格式化程序(4,6);
*字符串beautyDisplay=df.format(horribleNumber);
*字符串beautyLabel=df.formatHtml(horribleNumber);
*
*操作NumberFormat的3个实例以有效地格式化大量的双精度值。
*(避免在每次调用format()时创建对象编号格式)。
*
*将重用NumberFormat的3个实例来格式化值v:
*
*如果v0){
结果追加(s.子串(0,p1));
结果追加(“”);
}否则{
p1=0;
}
int p2=s.lastIndexOf('e');
如果(p2>0){
结果追加(s.子串(p1,p2));
结果追加(“”);
结果追加(s.substring(p2,s.length());
结果追加(“”);
}否则{
结果追加(s.substring(p1,s.length());
如果(p1==0){
结果追加(“”);
}
}
返回resu.toString();
}
}
注意:我使用了库中的两个函数。如果您不使用番石榴,请自己编写代码:

/**
 * 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();
}
/**
*相当于字符串。重复番石榴库中的(“#”),n):
*/
私有静态字符串createSharp(int n){
StringBuilder sb=新的StringBuilder();

对于(int i=0;i,如果想法是打印存储为双精度的整数,就像它们是整数一样,否则以最低必要精度打印双精度:

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
232
0.18
1237875192
4.58
0
1.2345

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

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

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);
    }
}
这是一个较长的、可能更糟的方法:

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;
}
公共静态字符串格式floatToString(最终浮点f)
{
最后一个字符串s=Float.toString(f);
int dotPos=-1;

对于(int i=0;i这里有一个实际有效的答案(这里是不同答案的组合)


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

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

简而言之:

如果要消除尾随零和问题,则应使用:

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.println
    FloatingDecimal.toJavaFormatString
    使用科学符号
    public static String removeTrailingZeros(double f)
    {
        if(f == (int)f) {
            return String.format("%d", (int)f);
        }
        return String.format("%f", f).replaceAll("0*$", "");
    }
    
    public static String prettyPrint(double d) {
      int i = (int) d;
      return d == i ? String.valueOf(i) : String.valueOf(d);
    }
    
    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 myValue = 0.00000021d;
     String.format("%s", myvalue); //output: 2.1E-7
    
     double myValue = 0.00000021d;
     String.format("%.12f", myvalue); // Output: 0.000000210000
    
     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
    
     double myValue = 0.00000021d;
     DecimalFormat df = new DecimalFormat("0");
     df.setMaximumFractionDigits(340);
     System.out.println(df.format(myvalue)); // Output: 0,00000021
    
    if (d % 1.0 != 0)
        return String.format("%s", d);
    else
        return String.format("%.0f", d);
    
    0.12
    12
    12.144252
    0
    
        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
    
        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;
    }
    
    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
    
    if (d == Math.floor(d)) {
        return String.format("%.0f", d); //Format is: 0 places after decimal point
    } else {
        return Double.toString(d);
    }
    
    if(n % 1 == 0) {
        return String.format(Locale.US, "%.0f", n));
    } else {
        return String.format(Locale.US, "%.1f", n));
    }
    
        public static String removeZero(double number) {
            DecimalFormat format = new DecimalFormat("#.###########");
            return format.format(number);
        }
    
    new DecimalFormat("00.#").format(20.236)
    //out =20.2
    
    new DecimalFormat("00.#").format(2.236)
    //out =02.2
    
    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);
    }
    
      private static String format(final double dbl) {
        return dbl % 1 != 0 ? String.valueOf(dbl) : String.valueOf((int) dbl);
      }
    
    /**
     * 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
    
    fun Double.toPrettyString() =
        if(this - this.toLong() == 0.0)
            String.format("%d", this.toLong())
        else
            String.format("%s", this)
    
    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
    
       /**
         * 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
        }
    
    /**
     * 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;
    }