首页 > 解决方案 > 将字符串解析为 Integer/Long/Float/Double

问题描述

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

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

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

标签: javatype-deduction

解决方案


为什么不使用 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;
}

推荐阅读