How do I parse ANY Number type from a String in Java?

五迷三道 提交于 2021-01-03 07:26:09

问题


How do I parse ANY Number type from a String in Java?

I'm aware of the methods like Integer.parseInt(myString) and Double.parseDouble(myString) but what I optimally want is a method like Number.parseNumber(myString) which doesn't exist. How can I achieve that behaviour in another way? (I want the parsed Number to reflect the String "exactly" in terms of for example number of decimals).

Example:

"0" => Number (internally of Integer subclass)

"0.0" => Number (internally of Double subclass)

Also, no ugliness like checking for decimal separators etc.


回答1:


Number number = NumberFormat.getInstance().parse(myString);

Seems to do the trick...




回答2:


Better way is to use BigDecimal class.

BigDecimal n = new BigDecimal("1.0");

Methods for needed values

n.byteValue();  
n.intValue();  
n.shortValue();  
n.longValue();  
n.floatValue();  
n.doubleValue();



回答3:


You are probably looking for BigDecimal.

Please remember that a number can be represented in many forms as a string. e.g. 1 is the same number as 1.0000000.



来源:https://stackoverflow.com/questions/33018208/how-do-i-parse-any-number-type-from-a-string-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!