java - 将字符串解析为 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。
解决方案
为什么不使用 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;
}
推荐阅读
- python - 使用 facebook api 访问新闻提要
- vb.net - 如何在外部应用程序中打开 .jpg 文件
- ffmpeg - 是否可以在ffmpeg中为文本添加笔画
- image - ResNet 快捷方式下采样
- camera - CameraLink 接口在运行时失败
- ocaml - Ocaml 尾递归版本
- java - System.getProperty("user.home") 返回 null
- html - WordPress 可视化编辑器和文本编辑器问题
- mysql - 如何正确使用 IN 子句从 MySQL 中的另一列获取值?
- multithreading - 使用 Dask 进行内存 Numpy 计算的工人与线程