java - 解析带有负后缀的数字

标签 java number-formatting decimalformat

有人可以向我解释为什么下面的代码会给出这个输出吗?

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/

相关文章:

java - 找不到 com.android.tools.build :gradle:7. 0.3

java - 多次尝试修复 : Malformed input or input contains unmappable chacraters 后,Eclipse 中出现连续 Git 错误

java - 运行引用同一包/目录中另一个类文件的类文件(来自 cmd)时出现 noClassDefFound 错误

clojure - 如何在 Clojure 中惯用地打印货币?

javascript - 如何将for循环Javascript程序格式化为小数点后两位?

java - 四舍五入到 2 位小数并通过 TextView

java - 每次我使用终端命令构建项目时,cordova 项目 native 应用程序中的 config.xml 都会更新

c - printf 不打印正确的浮点值

gnuplot - 与 gnuplot 格式说明符 %t 和 %T 不一致?

java - float 格式问题