Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing number with negative suffix

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?

like image 844
Oskar Kjellin Avatar asked Jul 02 '12 18:07

Oskar Kjellin


1 Answers

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 !

like image 187
cporte Avatar answered Oct 13 '22 08:10

cporte