568

64 ビットの double は、整数 +/- 2 53を正確に表すことができます。

この事実を考慮して、すべての型に対して double 型を single 型として使用することにしました。これは、最大の整数が符号なし 32 ビット数であるためです。

しかし今、これらの疑似整数を出力する必要がありますが、問題はそれらが実際の double と混在していることです。

では、これらの double を 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...)ロケールに依存することに注意してください(以下の回答を参照)。

4

28 に答える 28

442

double として格納された整数を整数であるかのように出力し、それ以外の場合は必要最小限の精度で double を出力することを考えている場合:

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()orSystem.out.printlnまたはFloatingDecimal.toJavaFormatStringdouble が 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 ロケールを使用すると、プログラムがどこで実行されても、小数点を確実に取得できます。

なぜ340を使用するのsetMaximumFractionDigitsですか?

2 つの理由:

  • setMaximumFractionDigits整数を受け入れますが、その実装では許可される最大桁数DecimalFormat.DOUBLE_FRACTION_DIGITSは 340 です。
  • Double.MIN_VALUE = 4.9E-324したがって、340桁の場合、doubleを丸めて精度を失うことはありません
于 2014-08-14T12:35:14.637 に答える
39

Use:

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

This should work with the extreme values supported by Double. It yields:

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

私の2セント:

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 に答える
11

とを使用しDecimalFormatますsetMinimumFractionDigits(0)

于 2017-10-10T19:59:21.800 に答える
5

DoubleFormatter多数の double 値を見栄えの良い文字列に効率的に変換するために を作成しました。

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 は 10 進数の桁数を決定します (銀行家の四捨五入でトリム)

ここにコード:

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ライブラリの 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();
}
于 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 型で数値を保存することを選択したと言いました。整数を 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

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 に答える
0

これを達成するための 2 つの方法を次に示します。まず、より短い(そしておそらくより良い)方法:

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 に答える
-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 は、小数点以下 2 桁に丸めます。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 に答える