Parse number with positive/negative prefix from st

2020-02-12 04:29发布

It's quite straight forward in java to parse number from String, i.e. with Integer.parseInt(s) if string in the format 'n' or '-n', but unfortunately it fails to parse string in the format of '+n'.

So what is the most effective/elegant way to parse number from string in java if it contains positive or negative prefix: '+n' or '-n' ?

2条回答
等我变得足够好
2楼-- · 2020-02-12 04:38

Just FYI, this has been fixed in Java 7.

from, Java SE8 for the Really Impatient

Prior to JDK 1.7, what was the result of the following code segment?

double x = Double.parseDouble("+1.0");

int n = Integer.parseInt("+1");

Pat yourself on the back if you knew the answer: +1.0 has always been a valid floating-point number, but until Java 7, +1 was not a valid integer. This has now been fixed for all the various methods that construct int, long, short, byte, and BigInteger values from strings. There are more of them than you may think. In addition to parse (Int|Long|Short|Byte), there are decode methods that work with hexadecimal and octal inputs, and valueOf methods that yield wrapper objects. The BigInteger(String) constructor is also updated.

查看更多
家丑人穷心不美
3楼-- · 2020-02-12 04:47
Integer.parseInt(s.replace("+", ""));

In truth there are many gotchas using Integer to parse numbers like that, in that Integer has very specific bounds of size and format ("1,000,000.00") isn't parsing that way, but I'm taking your question as Integer.parseInt meets your needs just fine, you just have to deal with a + in your data.

查看更多
登录 后发表回答