Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse number with positive/negative prefix from string in java

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' ?

like image 807
Gennady Shumakher Avatar asked Jan 18 '10 22:01

Gennady Shumakher


1 Answers

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.

like image 173
Yishai Avatar answered Oct 20 '22 21:10

Yishai