将字符串解析为整数/长/浮点/双精度

时间:2018-10-11 07:18:47

标签: java type-deduction

我正在尝试正确解析数字的字符串表示形式。 解析器为我提供了数值Integer / Long / Float / Double,但是当我尝试使用NumberFormat解析时:

String number = "1.0";
NumberFormat.getNumberInstance().parser(number);

它返回Long类型。但是,当我尝试解析“ 1.1”时,它会正确推断出Double(为什么不浮动?)。 我应该编写自己的数字解析器,还是可以对其进行适当地推断类型的方式进行调整。整数作为整数(不长)。浮点数为浮点数(不是Double)。长倍长,两倍长。

1 个答案:

答案 0 :(得分:1)

为什么不使用Java的内置数字解析器?

Double.parseDouble() Float.parseFloat() Integer.parseInt()

以此类推...

编辑:

查看您的评论后,您可以尝试使用

    String number = "1.0";
    if (isInteger(number)) {
        //parse Int
    } else if (isDouble(number)){
        //parse Double
    }

和方法:

public static boolean isInteger(String s) {
    try {
        Integer.parseInt(s);
    } catch (NumberFormatException e) {
        return false;
    }
    return true;
}

public static boolean isDouble(String s) {
    try {
        Double.parseDouble(s);
    } catch (NumberFormatException e) {
        return false;
    }
    return true;
}

public static boolean isFloat(String s) {
    try {
        Float.parseFloat(s);
    } catch (NumberFormatException e) {
        return false;
    }
    return true;
}
相关问题