Poechant 解讀 Java API —— 藉助貨幣格式化,初識 Locale 和 NumberFormat

鍾超發表於2011-10-30

Locale 屬於 java.util.Locale 包

NumberFormat 屬於 java.text.NumberFormat 包

	NumberFormat java.text.NumberFormat.getCurrencyInstance();
	NumberFormat java.text.NumberFormat.getCurrencyInstance(java.util.Locale);
	String java.util.NumberFormat.format(long);
	String java.util.NumberFormat.format(int);
	String java.util.NumberFormat.format(double);
	String java.util.NumberFormat.format(float);

入門的使用是比較簡單的,以下面程式碼為例

import java.text.NumberFormat;
import java.util.Locale;

public class Test {
	public static void main(String[] args) {
		LocaleTest.print();
	}
}

class LocaleTest {
	static public void print() {
		String countries[] = {
				"China",
				"Canada",
				"Korea",
				"Taiwan",
				"France",
				"Italy",
				"Japan",
				"Germany",
				"US",
				"UK"
		};
		Locale locale[] = {
				Locale.CHINA,
				Locale.CANADA,
				Locale.KOREA,
				Locale.TAIWAN,
				Locale.FRANCE,
				Locale.ITALY,
				Locale.JAPAN,
				Locale.GERMANY,
				Locale.US,
				Locale.UK
		};
		int len = countries.length;
		for (int i = 0; i < len; ++i) {
			System.out.println(countries[i] + ": " + NumberFormat.getCurrencyInstance(locale[i]).format(120000));
		}
	}
}

相關文章