如何使用Java';“的s十进制格式”;“聪明的”;货币格式?

如何使用Java';“的s十进制格式”;“聪明的”;货币格式?,java,formatting,decimalformat,Java,Formatting,Decimalformat,我想使用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.00”,而不仅仅是“$100

我想使用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.00”,而不仅仅是“$100”。

试试看

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
使用数字格式:

NumberFormat n = NumberFormat.getCurrencyInstance(Locale.US); 
double doublePayment = 100.13;
String s = n.format(doublePayment);
System.out.println(s);
另外,不要使用双精度来表示精确的值。如果您使用的货币值类似于蒙特卡罗方法(值无论如何都不精确),则首选double


另请参见:

是否必须使用
十进制格式

如果没有,则以下操作应该可以正常工作:

String currencyString = NumberFormat.getCurrencyInstance().format(currencyNumber);
//Handle the weird exception of formatting whole dollar amounts with no decimal
currencyString = currencyString.replaceAll("\\.00", "");
试用

DecimalFormat.setMinimumFractionDigits(2);
DecimalFormat.setMaximumFractionDigits(2);
您可以检查“数字是否完整”并选择所需的数字格式

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
printf也可以工作

例如:

双任意数=100; printf(“值为%4.2f”,任意数字)

输出:

该值为100.00


4.2表示强制数字在小数点后有两位数字。4控制小数点右边的位数。

您可以使用以下格式:


DecimalFormat dformat=新的DecimalFormat($。$)

我知道太晚了。然而,以下几点对我起了作用:

DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.UK);
new DecimalFormat("\u00A4#######0.00",otherSymbols).format(totalSale);

 \u00A4 : acts as a placeholder for currency symbol
 #######0.00 : acts as a placeholder pattern for actual number with 2 decimal 
 places precision.   

希望这有助于以后阅读本文的人:)

您可以根据以下条件使用两个不同的
DecimalFormat
对象进行尝试:

double d=100;
double d2=100.5;
double d3=100.41;

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

if(d%1==0){ // this is to check a whole number
    DecimalFormat df2=new DecimalFormat("'$'");
    System.out.println(df2.format(d));
}

System.out.println(df.format(d2));
System.out.println(df.format(d3));

Output:-
$100
$100.50
$100.41

您可以使用JavaMoneyAPI来实现这一点。(虽然这不是使用DecialFormat)


顺便说一句,使用双精度表示货币价值是一个坏主意:顺便说一句,大多数价格在银行中表示为
double
(或
int
,具有固定精度)。这不适用于案例1。。。它将100格式化为“$100.00”,而不是“$100”十进制格式(“0.00”),用于解析为双精度。谢谢你的简单回答这不适用于案例1。。。它将100格式化为“$100.00”而不是“$100”是的,这不包括setMinimumFractionDigits(0)的情况。它包括
code
public class Testing{/***@param args*/public static void main(String[]args){double d=100.5;DecimalFormat df=new DecimalFormat(“$'0.###”);df.setMaximumFractionDigits(2);df.setMinimumFractionDigits(2);String currency=df.format(d);System.out.println(currency)}
code
@Peter,你是说案例1吗?这就是为什么这似乎不起作用的地方(mac上的Java 1.6.0_22),产生“$100.00”而不是OP想要的“$100”。@Jonik是的,很抱歉输入错误。我基本上已经确定使用DecimalFormat是不可能的,并且已经转向其他方法来解决这个问题。谢谢好的,你是对的,如果你测试
code
if(currency.substring(currency.indexOf(“.”)。equals(“00”){currency=currency.substring(0,currency.indexOf(“.”)}
code
'currencyString.replaceAll(regexp,String)”在这种情况下效率低下,你可以尝试对它进行“破解”currencyString=currencyString.replace(“.00”和“);”它的效率要高得多。replaceAll需要编译模式、创建匹配器等。这可能会非常昂贵,尤其是当代码在资源有限的移动设备(Android)上的显示循环中执行时。值得注意的是,
NumberFormat.getCurrencyInstance()
仅在
Locale
设置为US时使用$进行格式化。要明确指定货币,您可以传递一个
Locale
——例如
NumberFormat.getCurrencyInstance(Locale.US)
,它不处理为较大的数字添加逗号,但在给定的示例中可以工作。
long amountInCents = ...;
double amountInEuro = amountInCents / 100.00;

String customPattern; 
if (minimumOrderValueInCents % 100 == 0) {
    customPattern = "# ¤";
} else {
    customPattern = "#.## ¤";
}

Money minDeliveryAmount = Money.of(amountInEuro, "EUR");
MonetaryAmountFormat formatter = MonetaryFormats.getAmountFormat(AmountFormatQueryBuilder.of(Locale.GERMANY)
            .set(CurrencyStyle.SYMBOL)
            .set("pattern", customPattern)
            .build());

System.out.println(minDeliveryAmount);