How to use Java's DecimalFormat for “smart” currency formatting?

前端 未结 10 570
旧巷少年郎
旧巷少年郎 2021-01-01 09:34

I\'d like to use Java\'s DecimalFormat to format doubles like so:

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

Th

10条回答
  •  一整个雨季
    2021-01-01 10:32

    You could use the Java Money API to achieve this. (although this is not using 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);
    

提交回复
热议问题