java 将字符串解析为具有空值的Double [duplicate]

qojgxg4l  于 2023-01-16  发布在  Java
关注(0)|答案(1)|浏览(134)
    • 此问题在此处已有答案**:

What is the difference between Double.parseDouble(String) and Double.valueOf(String)?(6个答案)
四年前关闭了。
我必须将字符串转换为双精度数,但可能我有一个空值。它是否适用于Double.parseDouble(stringValue)Double.valueOf(stringValue)
这两种方法有什么区别?
先谢谢你。

4ioopgfo

4ioopgfo1#

这两种方法都没有什么区别,都将抛出一个NullPointerExecption。相反,您需要添加一个helper方法,它将返回一个Double

static Double parseDouble(String s) {
    return s == null ? null : Double.parseDouble(s);
}

也可以使用缺省值返回double

static double parseDouble(String s, double otherwise) {
    return s == null ? otherwise : Double.parseDouble(s);
}

合适的值可以是Double.NaN

static double parseDouble(String s) {
    return s == null ? Double.NaN : Double.parseDouble(s);
}

相关问题