Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

java - How to get NumberFormat instance from currency code?

How can I get a NumberFormat (or DecimalFormat) instance corresponding to an ISO 4217 currency code (such as "EUR" or "USD") in order to format prices correctly?

Note 1: The problem I'm having is that the NumberFormat/DecimalFormat classes have a getCurrencyInstance(Locale locale) method but I can't figure out how to get to a Locale object from an ISO 4217 currency code.

Note 2: There is also a java.util.Currency class which has a getInstance(String currencyCode) method (returning the Currency instance for a given ISO 4217 currency code) but again I can't figure out how to get from a Currency object to a NumberFormat instance...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm not sure I understood this correctly, but you could try something like:

public class CurrencyTest
{
    @Test
    public void testGetNumberFormatForCurrencyCode()
    {
        NumberFormat format = NumberFormat.getInstance();
        format.setMaximumFractionDigits(2);
        Currency currency = Currency.getInstance("USD");
        format.setCurrency(currency);

        System.out.println(format.format(1234.23434));
    }   
}

Output:

1,234.23

Notice that I set the maximum amount of fractional digits separately, the NumberFormat.setCurrency doesn't touch the maximum amount of fractional digits:

Sets the currency used by this number format when formatting currency values. This does not update the minimum or maximum number of fraction digits used by the number format.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...