【问题标题】:Parse negative number with parentheses [duplicate]用括号解析负数[重复]
【发布时间】:2014-04-11 13:46:13
【问题描述】:

如何在java中将字符串“(123,456)”转换为-123456(负数)?

例如:

(123,456) = -123456

123,456 = 123456

我使用了 NumberFormat 类,但它只转换正数,不能处理负数。

NumberFormat numberFormat = NumberFormat.getInstance();
try {
       System.out.println(" number formatted to " + numberFormat.parse("123,456"));
       System.out.println(" number formatted to " + numberFormat.parse("(123,456)"));
    } catch (ParseException e) {
           System.out.println("I couldn't parse your string!");
    }

输出:

数字格式为 123456

我无法解析你的字符串!

【问题讨论】:

    标签: java parsing


    【解决方案1】:

    没有自定义解析逻辑的简单技巧:

    new DecimalFormat("#,##0;(#,##0)", new DecimalFormatSymbols(Locale.US)).parse("(123,456)")
    

    DecimalFormatSymbols 参数可以省略以使用当前语言环境进行解析

    【讨论】:

      【解决方案2】:

      你可以试试:

          try {
              boolean hasParens = false;
              String s = "123,456";
              s = s.replaceAll(",","")
      
              if(s.contains("(")) {
                  s = s.replaceAll("[()]","");
                  hasParens = true;
              }
      
              int number = Integer.parseInt(s);
      
              if(hasParens) {
                  number = -number;
              }
          } catch(...) {
          }
      

      也许有更好的解决方案

      【讨论】:

      • 在将其设置为负数之前,您需要检查是否存在括号。
      • 哎呀,我没看过那部分。我修复了,但可能有更好的解决方案
      • 您可以使用 s.replaceAll("[(),]", "") 一次性替换所有内容。
      • 很好,我不知道。考虑到:-)
      【解决方案3】:

      API 不同,但值得一试

          DecimalFormat myFormatter = new DecimalFormat("#,##0.00;(#,##0.00)");
          myFormatter.setParseBigDecimal(true);
          BigDecimal result = (BigDecimal) myFormatter.parse("(1000,001)");
          System.out.println(result);         
          System.out.println(myFormatter.parse("1000,001"));
      

      输出:

      -1000001 和 1000001

      【讨论】:

        【解决方案4】:

        我有其他解决方案:

            String s = "123,456";
            Boolean parenthesis = s.contains("(");
        
            ScriptEngineManager mgr = new ScriptEngineManager();
            ScriptEngine engine = mgr.getEngineByName("JavaScript");
        
            Object eval = mgr.eval(s);
        
            if(eval instanceof Double){
                int result = (int) ((Double)eval) * 1000;
                result *= (parenthesis ? -1 : 1);
           }
        

        这是一个非典型的解决方案,即使有重复的帖子,我认为这个答案是值得的:)

        【讨论】:

          【解决方案5】:

          这应该可行:

          public static void main(String[] args) {
              String negative = "(123,456)";
              String positive = "123,456";
          
              System.out.println("negative: " + parse(negative));
              System.out.println("positive: " + parse(positive));
          }
          
          private static Integer parse(String parsed) {
              if (parsed.contains("(") || parsed.contains(")")) {
                  parsed = parsed.replaceAll("[(),]", "");
                  return Integer.valueOf(parsed) * -1;
              } else {
                  parsed = parsed.replaceAll("[,]", "");
                  return Integer.valueOf(parsed);
              }
          }
          

          输出将是:

          否定:-123456
          正面:123456

          【讨论】:

            【解决方案6】:

            这里,我正在尝试将字符串更改为整数,然后再将整数更改为字符串。

            双斜杠 ('\\') 用于转义特殊字符,如果出现多次,它们很有用。

            这是完整的代码:测试并执行。

                package com.siri;
            
                import java.text.NumberFormat;
                import java.text.ParseException;
            
                /* Java program to demonstrate how to implement static and non-static
                   classes in a java program. */
                class NumberFormat
                {        
                   // How to create instance of static and non static nested class?
                   public static void main(String args[])
                   {        
                      NumberFormat numberFormat = NumberFormat.getInstance();
                      try 
                      {
                         System.out.println(" number formatted to " + 
                                            numberFormat.parse("123,456"));
            
                         String numberToBeChanged="(123,456)";
                         if(numberToBeChanged.contains("(") || 
                            numberToBeChanged.contains(")"))
                         {
                            numberToBeChanged=numberToBeChanged.replaceAll("\\(", 
                            "").replaceAll("\\)", "").replaceAll(",", "");
            
                            int numberToBeChangedInt = Integer.parseInt(numberToBeChanged);
                            numberToBeChangedInt *= -1;
                            numberToBeChanged = Integer.toString(numberToBeChangedInt);
                         }
            
                         System.out.println(" number formatted to " + 
                                            numberFormat.parse(numberToBeChanged));
            
                         } 
                         catch (ParseException e) 
                         {
                            System.out.println("I couldn't parse your string!");
                         }
                    }
                }
            

            现在您可以看到指定的预期结果。

            【讨论】:

              【解决方案7】:
              private int getIntValue(String numberToParse) {
                  if (numberToParse.contains("(")) {
                      numberToParse = numberToParse.replaceAll("[(),]", "");
                      return Integer.valueOf(numberToParse) * -1;
                  } else {
                      numberToParse = numberToParse.replaceAll("[,]", "");
                      return Integer.valueOf(numberToParse);
                  }
              }
              

              【讨论】:

                【解决方案8】:

                你可以这样试试:

                private static Pattern PATTERN = Pattern.compile("(\\()?(\\d+.*)(\\))?");
                
                public static void main(String[] args) throws ParseException {
                    System.out.println(parseLong("123,456"));
                    System.out.println(parseLong("(123,456)"));
                }
                
                private static long parseLong(String string) throws ParseException {
                    Matcher matcher = PATTERN.matcher(string);
                    if (matcher.matches()) {
                        long value = NumberFormat.getInstance(Locale.US).parse(matcher.group(2)).longValue();
                        return matcher.group(1) != matcher.group(3) ? value = -value : value;
                    }
                    throw new IllegalArgumentException("Invalid number format " + string);
                }
                

                输出:

                 123456
                -123456
                

                【讨论】:

                  【解决方案9】:

                  如果您确定只显示具有给定格式的字符串,那么为什么不在解析之前简单地将前导“(”替换为减号,将最后的“)”替换为空:

                  DecimalFormat numberFormat = DecimalFormat.getInstance();
                  
                  String number = "(123,456)";
                  System.out.println(" number formatted to " + 
                                       numberFormat.parse(number.replaceAll("(","-").replace All(")","")));
                  

                  【讨论】:

                  • 这不是万无一失的。它从原始字符串中删除了否定性。括号表示否定。
                  • 啊,我明白了。 NumberFormat 显然无法处理负数。但是使用DecimalFormat 应该可以让它工作,对吧?
                  • 我错过了用连字符替换左括号的部分。但我不确定您是否还需要删除逗号。
                  • DecimalFormat 能够处理逗号。默认情况下,它们被视为分组分隔符developer.android.com/reference/java/text/DecimalFormat.html
                  【解决方案10】:

                  你可以实现你所需要的:

                      try {
                          String var = "(123,456)";
                          Integer i = -Integer.parseInt(var.replaceAll("\\(", "")
                                  .replaceAll(",", "").replaceAll("\\)", ""));
                          System.out.println("Integer: " + i);
                      } catch (NumberFormatException e) {
                          System.out.println("Invalid number: " + e.getMessage());
                      }
                  

                  【讨论】:

                  • 你不应该假设字符串是负数。如果你只是用连字符替换左括号,它会更安全。
                  • 我不是假设字符串是负数我否定它,因为它被请求:)
                  • 如果你看一下 OP 的例子,他会传入两个字符串——一个是负数,一个是非负数。这可以概括为一个可以轻松处理两者的函数。
                  【解决方案11】:

                  尝试以下方法:

                  private int getInt(String s) {
                      return s.contains("(") ? 
                          -1 * Integer.parseInt(s.replaceAll("[(),]","")) : 
                              Integer.parseInt(s.replaceAll("[,]",""));
                  }  
                  

                  这将检查字符串是否包含“(”。如果是,它将删除所有'('和')'字符,将字符串转换为整数并使值变为负数。否则,它会删除', ' 字符并解析整数,因此是正数。

                  【讨论】:

                  • 你能解释一下你的代码,它会解决问题吗?
                  • 已添加说明。我相信它可以解决问题。
                  猜你喜欢
                  • 2019-11-17
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2015-10-12
                  • 2019-07-10
                  • 1970-01-01
                  • 2019-06-10
                  • 2013-11-04
                  相关资源
                  最近更新 更多