【问题标题】:Parsing number with negative suffix解析带负后缀的数字
【发布时间】:2012-07-03 04:48:55
【问题描述】:

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

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

后缀不打算用于解析吗?

【问题讨论】:

  • parse 不能保证消耗整个字符串。当它遇到一个不知道如何处理的角色时,它会停止。
  • @PeterLawrey 我知道,但我想我在设置后缀时告诉它该怎么做?为什么它处理 + 而不是 -?
  • 为了记录,设置负前缀可以正确地与您的代码配合使用。我检查了 API,它几乎一文不值。我说要么只使用否定前缀,要么走其他路线。
  • @ConorSherman 问题是我无法控制输入。
  • 你能不能从输入字符串中去掉最后一个字符,用Integer.parseInt(input)之类的东西解析剩余的数字,如果最后一个字符是'-',然后乘以-1?

标签: java number-formatting decimalformat


【解决方案1】:

在 javadoc 中指定:

否定子模式是可选的;如果不存在,则以本地化减号为前缀的正子模式(在大多数语言环境中为“-”)

在你的例子中,解析器正在等待“-1.2-”,所以你必须添加这一行:

format.setNegativePrefix("");

祝你有美好的一天!

【讨论】:

  • 你试过那个代码了吗?发帖前我也试过了,还是不行
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-02
  • 1970-01-01
  • 2013-01-30
  • 1970-01-01
  • 2023-03-07
  • 2013-11-25
  • 2012-05-13
相关资源
最近更新 更多