[英]How do I parse ANY Number type from a String in Java?
How do I parse ANY Number type from a String in Java? 如何解析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. 我知道像
Integer.parseInt(myString)
和Double.parseDouble(myString)
这样的方法,但我最理想的是像Number.parseNumber(myString)
这样的方法,它不存在。 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).
(我希望解析后的Number能够根据例如小数位数“精确地”反映字符串)。
Example: 例:
"0" => Number (internally of Integer subclass) “0”=>数字(整数子类内部)
"0.0" => Number (internally of Double subclass) “0.0”=>数字(Double子类内部)
Also, no ugliness like checking for decimal separators etc. 此外,没有像检查小数分隔符等丑陋。
Number number = NumberFormat.getInstance().parse(myString);
似乎要做的伎俩......
Better way is to use BigDecimal class. 更好的方法是使用BigDecimal类。
BigDecimal n = new BigDecimal("1.0");
Methods for needed values 需要值的方法
n.byteValue();
n.intValue();
n.shortValue();
n.longValue();
n.floatValue();
n.doubleValue();
You are probably looking for BigDecimal . 您可能正在寻找BigDecimal 。
Please remember that a number can be represented in many forms as a string. 请记住,数字可以多种形式表示为字符串。 eg
1
is the same number as 1.0000000
. 例如,
1
与1.0000000
数字相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.