Number of pairs with a negative suffix

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

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, but I don't like repeating 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?

+5
source share
1 answer

As stated in javadoc:

A negative subpattern is optional; if not, then the positive subpattern with the localized minus prefix ('-' in most locales)

In your example, the parser is waiting for "-1.2-", so you need to add this line:

format.setNegativePrefix("");

Have a nice day!

+2
source

All Articles