Java DecimalFormat getCurrency()方法

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

Java DecimalFormat getCurrency()方法

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

语法:

public Currency getCurrency()

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

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

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

下面是上述函数的实现。

程序 1 :

// Java program to illustrate the// getCurrency() method  import java.text.DecimalFormat;import java.util.Currency;import java.util.Locale;  public class Main {    public static void main(String[] args)    {          // Get the Currency Instance        DecimalFormat deciFormat = new DecimalFormat();          // Stores the values        String values = deciFormat.getCurrency()                            .getDisplayName();          // Prints the currency        System.out.println(values);    }}

输出:

US Dollar

程序2 :

// Java program to illustrate the// getCurrency() method  import java.text.DecimalFormat;import java.util.Currency;import java.util.Locale;  public class Main {    public static void main(String[] args)    {          // Get the Currency Instance        DecimalFormat deciFormat = new DecimalFormat();          // Sets the currency to Canadian Dollar        deciFormat.setCurrency(            Currency.getInstance(                Locale.CANADA));          // Stores the values        String values = deciFormat.getCurrency()                            .getDisplayName();          // Prints the currency        System.out.println(values);    }}

输出:

Canadian Dollar

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

相关推荐