有人可以向我解释为什么下面的代码会给出这个输出吗?
1.2
null
运行以下代码:
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)));
虽然这可行,但我不喜欢重复模式:
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)));
后缀不是用来解析的吗?
最佳答案
如 javadoc 中所指定:
The negative subpattern is optional; if absent, then the positive subpattern prefixed with the localized minus sign ('-' in most locales)
在你的例子中,解析器正在等待“-1.2-”,所以你必须添加这一行:
format.setNegativePrefix("");
祝你有美好的一天!
关于java - 解析带有负后缀的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11299319/