本示例向您展示如何使用DecimalFormatSymbols.setCurrencySymbol()方法更改已定义语言环境的货币符号。更改货币符号后,该DecimalFormatSymbols实例将传递给DecimalFormat进行格式化的对象。
package org.nhooo.example.text; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.NumberFormat; import java.util.Locale; public class CurrencyFormatSymbols { public static void main(String[] args) { double number = 123456.789; Locale[] locales = {Locale.CANADA, Locale.GERMANY, Locale.UK, Locale.ITALY, Locale.US}; String[] symbols = {"CAD", "EUR", "GBP", "ITL", "USD"}; for (int i = 0; i < locales.length; i++) { // 获取每个语言环境的货币格式值 // 不变的货币符号 DecimalFormat formatter = (DecimalFormat) NumberFormat.getCurrencyInstance(locales[i]); String before = formatter.format(number); // 为每个语言环境和集创建一个DecimalFormatSymbols // 它的新货币符号。 DecimalFormatSymbols symbol = new DecimalFormatSymbols(locales[i]); symbol.setCurrencySymbol(symbols[i]); // 将新的DecimalFormatSymbols设置为格式化程序对象。 formatter.setDecimalFormatSymbols(symbol); // 获取格式化值 String after = formatter.format(number); System.out.println(locales[i].getDisplayCountry() + " | before: " + before + " | after: " + after); } } }
这是我们程序的结果:
Canada | before: $123,456.79 | after: CAD123,456.79 Germany | before: 123.456,79 € | after: 123.456,79 EUR United Kingdom | before: £123,456.79 | after: GBP123,456.79 Italy | before: € 123.456,79 | after: ITL 123.456,79 United States | before: $123,456.79 | after: USD123,456.79