Java NumberFormat getCurrency()方法及示例

来源:这里教程网 时间:2026-02-17 20:59:28 作者:

Java NumberFormat getCurrency()方法及示例

getCurrency() 方法是 java.text.NumberFormat 的一个内置方法,用于返回用该货币格式化货币值时使用的货币。如果没有要确定的有效货币,或者以前没有设置过货币,它可以为空。

语法:

public Currency getCurrency()

参数 :该函数不接受单一参数。

返回值 :该函数返回在格式化货币值时使用的货币。

错误和异常 :当数字格式类没有实现货币格式化时,该函数会抛出UnsupportedOperationException。

下面是上述函数的实现。

程序 1 :

// Java program to implement// the above function  import java.text.NumberFormat;import java.util.Locale;  public class Main {    public static void main(String[] args)        throws Exception    {          // Get the instance        NumberFormat nF            = NumberFormat                  .getInstance();          // Stores the values        String values            = nF.getCurrency()                  .getDisplayName();          // Prints the currency        System.out.println(values);    }}

输出。

US Dollar

程序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 instance        NumberFormat nF            = NumberFormat                  .getNumberInstance();          // Sets the currency to Canadian Dollar        nF.setCurrency(            Currency.getInstance(                Locale.CANADA));          // Stores the values        String values            = nF.getCurrency()                  .getDisplayName();          // Prints the currency        System.out.println(values);    }}

输出。

Canadian Dollar

**参考资料: ** https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getCurrency()

相关推荐