Java NumberFormat getCurrencyInstance()方法及示例
getCurrencyInstance()
getCurrencyInstance() 方法是 java.text.NumberFormat 的一个内置方法,用于返回当前默认FORMAT地区的货币格式。
语法:
public static final NumberFormat getCurrencyInstance()参数 :该函数不接受任何参数。返回值 :该函数返回用于货币格式化的NumberFormat实例。
下面是上述函数的实现。
程序 1 :
// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the currency instance NumberFormat nF = NumberFormat .getCurrencyInstance(); // Sets the currency to Canadian Dollar nF.setCurrency( Currency.getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency() .getDisplayName(); int amount = 1078; // Prints the currency name System.out.println(values); // Print amount in defined currency System.out.println(nF.format(amount)); }}
输出
Canadian DollarCA$1,078.00
程序2
// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the currency instance NumberFormat nF = NumberFormat .getCurrencyInstance(Locale.US); // Stores the values String values = nF.getCurrency() .getDisplayName(); double amount = 2193.56; // Prints the currency System.out.println(values); // Print amount in defined currency System.out.println(nF.format(amount)); }}输出
US Dollar$2,193.56
**参考资料: ** https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getCurrencyInstance()
getCurrencyInstance(Locale inLocale)
getCurrencyInstance(Locale inLocale) 方法是 java.text.NumberFormat 的一个内置方法,用于返回任何指定地区的货币格式。
语法 :
public static NumberFormat getCurrencyInstance?(Locale inLocale)参数 :该函数接受一个强制性参数 inLocale ,该参数描述了要指定的语言环境。返回值 :该函数返回用于货币格式化的NumberFormat实例。
下面是上述函数的实现。
程序 1 :
// Java program to implement// the above functionimport java.text.NumberFormat;import java.util.Locale;import java.util.Currency;public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat .getCurrencyInstance( Locale.CANADA); // Stores the values String values = nF.getCurrency() .getDisplayName(); double amount = 4538.89; // Prints the currency System.out.println(values); // Print amount in defined currency System.out.println(nF.format(amount)); }}输出
Canadian Dollar$4,538.89
**参考资料: ** https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getCurrencyInstance(java.util.Locale)
