JAva double回転string

3062 ワード

JAvaではdouble回転stringはDouble.toString(d)方式で使用できます.しかし、この方法には隠れた穴があります.よく見てください.
package hello;

public class DoubleToString {

    public static void test1(double dou) {
        String dou_str = Double.toString(dou);
        if (dou_str.equals("20160101")) {
            System.out.println("YES!");
        } else {
            System.out.println("NO!");
        }
    }

    public static void main(String[] args) {
        double dou = 20160101;
        test1(dou);
    }
}

上記のコードを実行すると、コンソールは華麗に出力されます.
NO

6行目の後ろにdou_を印刷しますstr:
2.0160101E7

もともとjvmという商品はdoubleを科学カウント法でdoubleを表していたので、stringに変えてから変わったのも無理はありません.の
上のコードを次のように変更します.
package hello;

import java.text.NumberFormat;

public class DoubleToString {

    public static void test2(double dou) {
        Double dou_obj = new Double(dou);
        NumberFormat nf = NumberFormat.getInstance();
        nf.setGroupingUsed(false);
        String dou_str = nf.format(dou_obj);
        System.out.println("dou_str is:" + dou_str);
        if (dou_str.equals("20160101")) {
            System.out.println("YES!");
        } else {
            System.out.println("NO!");
        }
    }

    public static void main(String[] args) {
        double dou = 20160101;
        test2(dou);
    }
}

再運転、再出力、これでOK:
dou_str is:20160101
YES!