How to check if a String is numeric in Java

前端 未结 30 3487
盖世英雄少女心
盖世英雄少女心 2020-11-21 05:26

How would you check if a String was a number before parsing it?

30条回答
  •  佛祖请我去吃肉
    2020-11-21 05:59

    Parse it (i.e. with Integer#parseInt ) and simply catch the exception. =)

    To clarify: The parseInt function checks if it can parse the number in any case (obviously) and if you want to parse it anyway, you are not going to take any performance hit by actually doing the parsing.

    If you would not want to parse it (or parse it very, very rarely) you might wish to do it differently of course.

提交回复
热议问题