用括号解析负数

Sag*_*gar 7 java parsing

如何在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!");
    }
Run Code Online (Sandbox Code Playgroud)

输出:

数字格式为123456

我无法解析你的字符串!

Mar*_*gor 7

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

new DecimalFormat("#,##0;(#,##0)", new DecimalFormatSymbols(Locale.US)).parse("(123,456)")
Run Code Online (Sandbox Code Playgroud)

对于使用当前语言环境进行解析的情况,可以省略DecimalFormatSymbols参数


The*_*ube 5

你可以试试:

    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(...) {
    }
Run Code Online (Sandbox Code Playgroud)

虽然可能有更好的解决方案

  • 您可以使用 s.replaceAll("[(),]", "") 一次替换所有内容。 (2认同)

Day*_*oon 5

不一样的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"));
Run Code Online (Sandbox Code Playgroud)

输出:

-10000011000001