English 中文(简体)
如何使用Java的DecimalFormat进行“智能”货币格式化?
原标题:How to use Java s DecimalFormat for "smart" currency formatting?

我想使用Java的DecimalFormat来格式化双打,如下所示:

#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美元”。

问题回答

是否必须使用小数格式

如果没有,则以下内容看起来应该有效:

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

使用数字格式:

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

此外,不要使用双精度来表示精确的值。如果您在类似蒙特卡罗方法的方法中使用货币值(其中的值无论如何都不精确),则首选double。

另请参阅:编写Java程序来计算和格式化货币

尝试

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

尝试使用

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

您可以使用以下格式:

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

您可以使用Java Money API来实现这一点。(尽管这不是使用DecialFormat)

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

printf也起作用。

示例:

double anyNumber = 100; printf("The value is %4.2f ", anyNumber);

输出:

值为100.00

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





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签