Parsing number with negative suffix
Asked Answered
S

1

6

Can someone explain to me why the below code gives this output?

1.2
null

Running the following code:

String positive = "1.2+";
String negative = "1.2-";
DecimalFormat format = new DecimalFormat("0.0");
format.setPositiveSuffix("+");
format.setNegativeSuffix("-");  
format.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance(Locale.US));
System.out.println(format.parse(positive, new ParsePosition(0)));
System.out.println(format.parse(negative, new ParsePosition(0)));

This works though, but I do not like the repetition of the pattern:

String positive = "1.2+";
String negative = "1.2-";
DecimalFormat format = new DecimalFormat("0.0+;0.0-");  
format.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance(Locale.US));
System.out.println(format.parse(positive, new ParsePosition(0)));
System.out.println(format.parse(negative, new ParsePosition(0)));

Is the suffix not intended to be used for parsing?

Stepsister answered 2/7, 2012 at 18:40 Comment(9)
parse is not guaranteed to consume the whole string. It will stop when it gets a character it doesn't know what to do with.Jury
@PeterLawrey I know, but I thought I told it what to do when I set the suffix? And why does it handles + but not -?Stepsister
@PeterLawrey I would also assume that the second code is slower, as it would need to parse the whole string twice?Stepsister
I have to admit, I have never seen suffixes used. Perhaps its behaviour isn't what you want.Jury
@PeterLawrey Me neither. And googling for it yielded very little result. And the javadocs is useless to say the least. Thus my note in the end: is it not even used for parsing? Odd that I cannot find any documentation at allStepsister
For the record, setting a negative PREfix works correctly with your code. I checked the API and it is near worthless. I say either just use the negative prefix or go a different route.Angi
@ConorSherman The problem is that I have no control over the input.Stepsister
Could you strip off the last character from the input string, parse the remaining digits with something like Integer.parseInt(input), and then multiply by -1 if the last character was a '-'?Angi
@ConorSherman I could do that. But my second code that works is cleaner. My main question is why I get the results I getStepsister
F
2

As specified in the javadoc :

The negative subpattern is optional; if absent, then the positive subpattern prefixed with the localized minus sign ('-' in most locales)

In your exemple, the parser is waiting "-1.2-", so you have to add this line :

format.setNegativePrefix("");

Have a nice day !

Forwardness answered 4/7, 2012 at 6:53 Comment(1)
Did you try that code? I tried it as well before posting, did not work thoStepsister

© 2022 - 2024 — McMap. All rights reserved.