INDEX
[Java]NumberFormatクラスを利用して金額文字列を数値へ変換する
1  NI-Lab.  2003/11/03(Mon) 22:39
[Java]NumberFormatクラスを利用して金額文字列を数値へ変換する

/******************************************************************************
* @(#) $Id$
* Copyright (c) 2003 NI-Lab.
* Author: NI-Lab.
* Since: 2003/11/03
*****************************************************************************/
package info.nilab.sample;

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Currency;

/**
* <pre>
* 実行結果
* ---------------------------------------------------
* Currency Symbol: ¥
* 123 -> Unparseable number: "123"
* 123456 -> Unparseable number: "123456"
* \123 -> Unparseable number: "\123"
* \123,456 -> Unparseable number: "\123,456"
* ¥123 -> 123.0
* ¥123,456 -> 123456.0
* ¥123 -> 123.0
* ¥123,456 -> 123.0
* ¥123、456 -> 123.0
* ¥123・456 -> 123.0
* ¥123,456 -> 123456.0
* ¥-123 -> Unparseable number: "¥-123"
* ¥-123,456 -> Unparseable number: "¥-123,456"
* -¥123 -> -123.0
* -¥123,456 -> -123456.0
* \123 -> Unparseable number: "\123"
* \123,456 -> Unparseable number: "\123,456"
* ---------------------------------------------------
* </pre>
* @author NI-Lab.
*/
public class NumberFormatSample {

public static void main(String[] args) {

String[] list =
{
"123",
"123456",
"\\123",
"\\123,456",
"¥123",
"¥123,456",
"¥123",
"¥123,456",
"¥123、456",
"¥123・456",
"¥123,456",
"¥-123",
"¥-123,456",
"-¥123",
"-¥123,456",
"\u00a5123",
"\u00a5123,456",
};

NumberFormat nf = NumberFormat.getCurrencyInstance();
Currency c = nf.getCurrency();
System.out.println("Currency Symbol: " + c.getSymbol());

for (int i = 0; i < list.length; i++) {

String source = list[i];
String parsed;

try {
Number n = nf.parse(list[i]);
parsed = Double.toString(n.doubleValue());
} catch (ParseException e) {
parsed = e.getMessage();
}

System.out.println(source + " -> " + parsed);

}

}

}

2  NI-Lab.  2003/11/03(Mon) 22:46
↑Windows2000-JDK1.4.0 での実行結果(当然ロケールはJapan-Japaneseだろう)。

半角\記号が通貨記号だと思ってたけど、
上の結果を見ると、全角¥記号が通貨記号らしい。
U+00a5(YEN SIGN)もダメ?

数字は全角でもOKな感じ。
全角ハイフン(マイナス扱いとして)は試してないな……

3  NI-Lab.  2003/11/03(Mon) 22:57
全角ハイフンはパース不可。

--- 結果 ---
−¥123 -> Unparseable number: "−¥123"
−¥123,456 -> Unparseable number: "−¥123,456"

4  NI-Lab.  2003/11/03(Mon) 22:59
ついでに、数値から金額文字列への変換を試してみた。
日本では小数点以下の数値は金額として表示しない?

--- ソースコード ---
private static void format() {

double[] list = { 10.5, 105.0, 1050.0, };

NumberFormat nf = NumberFormat.getCurrencyInstance();

for (int i = 0; i < list.length; i++) {
double source = list[i];
String formatted = nf.format(source);
System.out.println(Double.toString(source) + " -> " + formatted);
}

}

--- 実行結果 ---
10.5 -> ¥10
105.0 -> ¥105
1050.0 -> ¥1,050