Java中的货币格式化
getCurrencyInstance()。静态方法,建立一个NumberFormat类的对象并返回引用,该引用指定货币格式为系统预设的货币格式。
getCurrencyInstance(Locale) 。静态方法,建立一个NumberFormat类的对象,并返回引用,该引用的货币格式由Locale指定。Locale类在java.util包中。
public static void main(String[] args) {
currencyFormat();
}
private static void currencyFormat() {
//按系统预设的货币格式输出,这里是人民币
NumberFormat nf = NumberFormat.getCurrencyInstance();
System.out.println(nf.format(123.456));//¥123.46
//按指定的货币格式输出,这里是美元
//Locale locale = Locale.US;
nf = NumberFormat.getCurrencyInstance(Locale.US);
System.out.println(nf.format(123.456));//$123.46
}
运行结果如下