How to get NumberFormat instance from currency code?

前端 未结 6 1354
無奈伤痛
無奈伤痛 2020-12-15 05:25

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

6条回答
  •  太阳男子
    2020-12-15 05:34

    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.

提交回复
热议问题