Parsing number with negative suffix

巧了我就是萌 提交于 2019-12-12 10:45:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!