问题
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