サンプル学ぶNumberFormatよくある使い方例 - 数字と文字列の相互変換
2010/04/13 17:17Update
サンプルからNumberFormatよくある使い方(文字列を数字に変換、数字を文字列(区切り、通貨、パーセンテージ)に変換など)を学びます。
TestNumberFormat.javapackage com.test.number;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
/**
* NumberFormatよくある使い方例
* 1)文字列を数字へ変換
* 2)数字を文字列(区切り、通貨、パーセンテージ)に変換
*
*/
public class TestNumberFormat {
public static void main(String []args) {
System.out.println("NumberFormat.parse(String)");
testParse();
System.out.println("NumberFormat.format()");
testFormat();
}
/**
* NumberFormat.parse(String)
*/
private static void testParse() {
try {
NumberFormat nf = NumberFormat.getInstance();
///////////////////////////////////////
//パーサー(文字列を数字に解析)
Number n = nf.parse("5");
printNumber(n);
//5.5
n = nf.parse("5.5");
printNumber(n);
//5.5f
n = nf.parse("5.5f");
printNumber(n);
//5.5d
n = nf.parse("5.5d");
printNumber(n);
//数値を整数としてのみ解析する
nf.setParseIntegerOnly(true);
n = nf.parse("5.5");
printNumber(n);
} catch (ParseException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
}
private static void printNumber(Number n) {
if (n instanceof Long) {
System.out.println("Long:" + n.longValue());
} else if (n instanceof Integer) {
System.out.println("Integer:" + n.intValue());
} else if (n instanceof Double) {
System.out.println("Double:" + n.doubleValue());
} else if (n instanceof Float) {
System.out.println("Float:" + n.doubleValue());
} else if (n instanceof Short) {
System.out.println("Short:" + n.shortValue());
}
}
//数字を文字列(区切りや通貨、パーセンテージ)に変換
private static void testFormat() {
//数字
String value = NumberFormat.getNumberInstance(Locale.JAPAN).format(123456.1234);
System.out.println(value);
//整数
value = NumberFormat.getIntegerInstance(Locale.JAPAN).format(123456.1234);
System.out.println(value);
//通貨
value = NumberFormat.getCurrencyInstance(Locale.JAPAN).format(123456.1234);
System.out.println(value);
//パーセンテージ
value = NumberFormat.getPercentInstance(Locale.JAPAN).format(0.12);
System.out.println(value);
}
}
実行結果:
NumberFormat.parse(String)
Long:5
Double:5.5
Double:5.5
Double:5.5
Long:5
NumberFormat.format()
123,456.123
123,456
¥123,456
12%
Long:5
Double:5.5
Double:5.5
Double:5.5
Long:5
NumberFormat.format()
123,456.123
123,456
¥123,456
12%
参考資料
NumberFormat API doc
Sponsored Link
- Relative Articles
- Java言語数字の基本型 - (2008/10/10 15:44)
- Java 数字に関するクラス 概要 - (2008/10/10 16:44)
- サンプルから学ぶ Java Integerよくある使い方 - (2009/03/10 14:52)
- Java正規表現一例 - 正規表現で 英字/数字の分離 - (2010/01/22 17:36)