サンプル学ぶNumberFormatよくある使い方例 - 数字と文字列の相互変換

2010/04/13 17:17Update
TAGS: NumberFormat | Number | 数字 | 文字列 | 区切り | 通貨 | パーセンテージ

サンプルからNumberFormatよくある使い方(文字列を数字に変換、数字を文字列(区切り、通貨、パーセンテージ)に変換など)を学びます。

TestNumberFormat.java
package 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%

参考資料


NumberFormat API doc

有关作者
Syboos.jp編集長システム設計や開発、保守運営などを行ってます。オープンソース技術に興味があります。

Sponsored Link


Comments