当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java NumberFormat setCurrency()用法及代码示例


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

用法:

public void setCurrency(Currency currency)

参数:该函数接受强制性参数Currency,该参数指定要设置的货币。


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

错误和异常:该函数引发两种类型的异常,如下所述:

  • UnsupportedOperationException:如果数字格式类未实现货币格式设置,则会抛出该错误
  • NullPointerException 如果currency为null则抛出

下面是上述函数的实现:

程序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

示例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 
    { 
        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://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#setCurrency(java.util.Currency)



相关用法


注:本文由纯净天空筛选整理自gopaldave大神的英文原创作品 NumberFormat setCurrency() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。