简体   繁体   English

在没有DecimalFormat的Java中使用模式解析数字

[英]Parsing numbers with pattern in Java without DecimalFormat

Is there a Java parsing library similar to DecimalFormat ? 有没有类似于DecimalFormat的Java解析库? I am unable to do what I want with DecimalFormat and regular expressions. 我无法使用DecimalFormat和正则表达式执行所需的操作。

I need to be able to: 我需要能够:

  • Parse only an integer (DecimalFormat needs more settings than just pattern) 仅解析一个整数(DecimalFormat不仅需要模式,还需要更多设置)
  • Parse decimal (precise no rounding) 解析十进制(精确无舍入)
  • Parse numbers like 123,456.789. 解析数字,例如123,456.789。 (DecimalFormat for ###,###.### accepts "123456789" as well) (###,###。###的DecimalFormat也接受“ 123456789”)

You could try treating it like a String and tokenizing it. 您可以尝试将其视为String并将其标记化。

str.split("\\\\.") will split out the decimal side and then substring it to your precision, then on the number side you could split(",") str.split(“ \\\\。”)将拆分出小数部分,然后将其子串化为您的精度,然后在数字方面可以拆分(“,”)

This is quite a bit of manual parsing work though... 不过,这是相当多的手动解析工作...

I would use Regexp and NumberFormat : 使用Regexp和NumberFormat

Map<Pattern,NumberFormat> POSSIBLE_FORMATS = ...;
String input = ...;
Number value = null;
for (Map.Entry<Pattern,NumberFormat> possible : POSSIBLE_FORMATS.entrySet()) {
  if (possible.getKey().matcher(input).matches()) {
    value = possible.getKeValue().parse(input);
    break;
  }
}
if (value == null) {
  throw new IllegalArgumentExcption("no valid input format: " + input);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM