Most elegant isNumeric() solution for java

前端 未结 7 873
囚心锁ツ
囚心锁ツ 2021-02-13 01:31

I\'m porting a small snippet of PHP code to java right now, and I was relying on the function is_numeric($x) to determine if $x is a number or not. Th

7条回答
  •  余生分开走
    2021-02-13 02:17

    It's usually a bad idea to have a number in a String. If you want to use this number then parse it and use it as a numeric. You shouldn't need to "check" if it's a numeric, either you want to use it as a numeric or not.

    If you need to convert it, then you can use every parser from Integer.parseInt(String) to BigDecimal(String)

    If you just need to check that the content can be seen as a numeric then you can get away with regular expressions.

    And don't use the parseInt if your string can contain a float.

提交回复
热议问题