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
相關用法
- Java DecimalFormatSymbols setCurrency()用法及代碼示例
- Java NumberFormat equals()用法及代碼示例
- Java NumberFormat getAvailableLocales()用法及代碼示例
- Java NumberFormat getCurrency()用法及代碼示例
- Java NumberFormat getMaximumFractionDigits()用法及代碼示例
- Java NumberFormat getNumberInstance()用法及代碼示例
- Java NumberFormat getInstance()用法及代碼示例
- Java NumberFormat getIntegerInstance()用法及代碼示例
- Java NumberFormat clone()用法及代碼示例
- Java NumberFormat setRoundingMode()用法及代碼示例
- Java NumberFormat parseObject()用法及代碼示例
- Java NumberFormat isParseIntegerOnly()用法及代碼示例
- Java NumberFormat setMinimumIntegerDigits()用法及代碼示例
- Java NumberFormat setGroupingUsed()用法及代碼示例
- Java NumberFormat parse()用法及代碼示例
注:本文由純淨天空篩選整理自gopaldave大神的英文原創作品 NumberFormat setCurrency() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。