need space between currency symbol and amount

前端 未结 5 812
余生分开走
余生分开走 2021-02-13 13:09

I\'m trying to print INR format currency like this:

NumberFormat fmt = NumberFormat.getCurrencyInstance();
fmt.setCurrency(Currency.getInstance(\"INR\"));
fmt.fo         


        
5条回答
  •  面向向阳花
    2021-02-13 13:29

    I don't see any easy way to do this. Here's what I came up with...

    The key to getting the actual currency symbol seems to be passing the destination locale into Currency.getSymbol:

    currencyFormat.getCurrency().getSymbol(locale)
    

    Here's some code that seems like it mostly works:

    public static String formatPrice(String price, Locale locale, String currencyCode) {
    
        NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(locale);
        Currency currency = Currency.getInstance(currencyCode);
        currencyFormat.setCurrency(currency);
    
        try {
            String formatted = currencyFormat.format(NumberFormat.getNumberInstance().parse(price));
            String symbol = currencyFormat.getCurrency().getSymbol(locale);
    
            // Different locales put the symbol on opposite sides of the amount
            // http://en.wikipedia.org/wiki/Currency_sign
            // If there is already a space (like the fr_FR locale formats things),
            // then return this as is, otherwise insert a space on either side
            // and trim the result
            if (StringUtils.contains(formatted, " " + symbol) || StringUtils.contains(formatted, symbol + " ")) {
                return formatted;
            } else {
                return StringUtils.replaceOnce(formatted, symbol, " " + symbol + " ").trim();
            }
        } catch (ParseException e) {
            // ignore
        }
        return null;
    }
    

提交回复
热议问题