[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);
}
}
}