问题
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?
回答1:
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 !
来源:https://stackoverflow.com/questions/11299319/parsing-number-with-negative-suffix