解析带有负后缀的数字 [英] Parsing number with negative suffix

查看:82
本文介绍了解析带有负后缀的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Can someone explain to me why the below code gives this output?

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)));

虽然这可行,但我不喜欢模式的重复:

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?

推荐答案

如 javadoc 中所述:

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)

在您的示例中,解析器正在等待-1.2-",因此您必须添加以下行:

In your exemple, the parser is waiting "-1.2-", so you have to add this line :

format.setNegativePrefix("");

祝你有美好的一天!

这篇关于解析带有负后缀的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆