Java 从字符串解析为数字,但推断类型

我正在尝试编写一个将字符串转换为数字的泛型方法。我可以使用哪个 API 来完成此操作。


private <T extends Number> T parseFromString(String str) {

   // convert str to number

}

然后致电:


   parseFromString<Double>("120.0");


   parseFromString<Integer>("11");


梵蒂冈之花
浏览 118回答 1
1回答

繁星点点滴滴

无需使用泛型,我只使用:private static Number parseFromString(String str) throws NumberFormatException {&nbsp; &nbsp; if (str.matches("\\d+")) {&nbsp; &nbsp; &nbsp; &nbsp; return Integer.valueOf(str);&nbsp; &nbsp; } else if (str.matches("[-+]?[0-9]*\\.?[0-9]+")) {&nbsp; &nbsp; &nbsp; &nbsp; return Double.valueOf(str);&nbsp; &nbsp; }&nbsp; &nbsp; throw new NumberFormatException("Number not correct");}输出System.out.println(parseFromString("11"));&nbsp; &nbsp; // 11System.out.println(parseFromString("112.3")); // 112.3System.out.println(parseFromString("some not correct strings")); // Number not correct或者正如@shmosel在他的评论中提到的,你可以只使用:private static Number parseFromString(String str) throws ParseException {&nbsp; &nbsp; return NumberFormat.getInstance().parse(str);}在此解决方案中,您可能会丢失精度,因此可能需要使用区域设置,如下所示:private static Number parseFromString(String str) throws ParseException {&nbsp; &nbsp; return NumberFormat.getInstance(Locale.CANADA).parse(str);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java