31

Java の DecimalFormat を使用して double を次のようにフォーマットしたいと思います。

#1 - 100 -> $100
#2 - 100.5 -> $100.50
#3 - 100.41 -> $100.41

これまでのところ、私が思いつくことができる最高のものは次のとおりです。

new DecimalFormat("'$'0.##");

しかし、これはケース #2 では機能せず、代わりに「$100.5」を出力します。

編集:

これらの回答の多くは、ケース #2 と #3 のみを考慮しており、その解決策によって #1 が 100 を「$100」ではなく「$100.00」にフォーマットされることに気づいていません。

4

10 に答える 10

23

使用する必要がありますDecimalFormatか?

そうでない場合は、次のように動作するはずです。

String currencyString = NumberFormat.getCurrencyInstance().format(currencyNumber);
//Handle the weird exception of formatting whole dollar amounts with no decimal
currencyString = currencyString.replaceAll("\\.00", "");
于 2011-02-17T19:15:14.683 に答える
7

NumberFormat を使用:

NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US); 
double doublePayment = 100.13;
String s = n.format(doublePayment);
System.out.println(s);

また、正確な値を表すために double を使用しないでください。モンテカルロ法などで通貨値を使用している場合 (値が正確ではない場合)、double が優先されます。

関連項目:通貨を計算してフォーマットする Java プログラムを作成する

于 2011-02-17T19:14:38.767 に答える
6

試す

new DecimalFormat("'$'0.00");

編集:

私は試した

DecimalFormat d = new DecimalFormat("'$'0.00");

        System.out.println(d.format(100));
        System.out.println(d.format(100.5));
        System.out.println(d.format(100.41));

そして得た

$100.00
$100.50
$100.41
于 2011-02-17T19:12:34.390 に答える
1

「数値全体かどうか」をチェックして、必要な数値形式を選択できます。

public class test {

  public static void main(String[] args){
    System.out.println(function(100d));
    System.out.println(function(100.5d));
    System.out.println(function(100.42d));
  }

  public static String function(Double doubleValue){
    boolean isWholeNumber=(doubleValue == Math.round(doubleValue));
    DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols(Locale.GERMAN);
    formatSymbols.setDecimalSeparator('.');

    String pattern= isWholeNumber ? "#.##" : "#.00";    
    DecimalFormat df = new DecimalFormat(pattern, formatSymbols);
    return df.format(doubleValue);
  }
}

あなたが望むものを正確に与えるでしょう:

100
100.50
100.42
于 2012-11-23T06:25:36.143 に答える
1

次の形式を使用できます。

DecimalFormat dformat = new DecimalFormat("$#.##");

于 2014-05-12T09:06:44.023 に答える
-1

printfも機能します。

例:

double anyNumber = 100; printf( "値は%4.2f"、anyNumber);

出力:

値は100.00です

4.2は、数値の小数点以下2桁を強制することを意味します。4は、小数点以下の桁数を制御します。

于 2013-03-08T03:04:19.827 に答える