Java parsing from string to numeric but infer type

问题: I am trying to write a generic method converting a string to number. Which API can I use to finish this. private <T extends Number> T parseFromString(String str) {...

问题:

I am trying to write a generic method converting a string to number. Which API can I use to finish this.

private <T extends Number> T parseFromString(String str) {
   // convert str to number
}

Then call :

   parseFromString<Double>("120.0");

   parseFromString<Integer>("11");

回答1:

No need to use generic, I would just use :

private static Number parseFromString(String str) throws NumberFormatException {
    if (str.matches("\d+")) {
        return Integer.valueOf(str);
    } else if (str.matches("[-+]?[0-9]*\.?[0-9]+")) {
        return Double.valueOf(str);
    }
    throw new NumberFormatException("Number not correct");
}

Outputs

System.out.println(parseFromString("11"));    // 11
System.out.println(parseFromString("112.3")); // 112.3
System.out.println(parseFromString("some not correct strings")); // Number not correct

Or as @shmosel mentioned in his comment, you can just use :

private static Number parseFromString(String str) throws ParseException {
    return NumberFormat.getInstance().parse(str);
}

In this solution you may lose precision, so it may required to use locale, like so :

private static Number parseFromString(String str) throws ParseException {
    return NumberFormat.getInstance(Locale.CANADA).parse(str);
}
  • 发表于 2019-03-29 01:40
  • 阅读 ( 154 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除