views:

254

answers:

1

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

+4  A: 
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.

Yishai
java.text.NumberFormat is probably the parser to use, but still doesn't solve the issue with "+". String.replace(), as demonstrated, does.
Matthew Flynn
Yes, indeed, I hoped there is some solution based on built-in parsers/formatters...
Gennady Shumakher
@Gennady Shumakher, can you elaborate on the range of possibilities of what you need to parse?
Yishai
@Yashai, I am OK with the solution, it's good enough for my use case. In generall, I just feel jdk could provide more elegant way to do that.
Gennady Shumakher
@Gennady, NumberFormat, as Matthew said, is the way to go for serious number parsing. The DecimalFormat subclass is probably the class you want.
Yishai