📌  相关文章
📜  Java中的 NumberFormat setCurrency() 方法及示例

📅  最后修改于: 2022-05-13 01:54:29.488000             🧑  作者: Mango

Java中的 NumberFormat setCurrency() 方法及示例

setCurrency()方法是Java.text.NumberFormat 的内置方法,它在格式化货币值时设置此数字格式使用的货币。这不会更新数字格式使用的最小或最大小数位数。它会覆盖最初的货币。

句法:

public void setCurrency(Currency currency)

参数:该函数接受一个强制参数currency ,它指定要设置的货币。

返回值:该函数不返回任何内容,因此返回类型为 void。

错误和异常:该函数抛出两种类型的异常,可描述如下:

  • UnsupportedOperationException : 如果数字格式类没有实现货币格式,则抛出它
  • NullPointerException如果货币为空则抛出

下面是上述函数的实现:

程序 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
    {
  
        NumberFormat nF
            = NumberFormat.getNumberInstance();
  
        // Initially currency
        System.out.println("Initially Currency: "
                           + nF.getCurrency());
  
        // Currency set to US
        nF.setCurrency(Currency
                           .getInstance(Locale.CANADA));
  
        // Print the currency
        System.out.println("Currency set as: "
                           + nF.getCurrency());
    }
}
输出:
Initially Currency: USD
Currency set as: CAD

方案二:

// 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
    {
        try {
  
            NumberFormat nF
                = NumberFormat.getNumberInstance();
  
            // Initially currency
            System.out.println("Initially Currency: "
                               + nF.getCurrency());
  
            // Currency set to US
            nF.setCurrency(null);
  
            // Print the currency
            System.out.println("Currency set as: "
                               + nF.getCurrency());
        }
        catch (Exception e) {
            System.out.println("Exception is: " + e);
        }
    }
}
输出:
Initially Currency: USD
Exception is: java.lang.NullPointerException

参考:https: Java Java.util.Currency)