Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse negative number with parentheses [duplicate]

Tags:

java

parsing

How to convert a string "(123,456)" to -123456 (negative number) in java?

Ex:

(123,456) = -123456

123,456 = 123456

I used NumberFormat class but it is converting positive numbers only, not working with negative numbers.

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!");
    }

Output:

number formatted to 123456

I couldn't parse your string!

like image 732
Sagar Avatar asked Apr 11 '14 13:04

Sagar


3 Answers

Simple trick without custom parsing logic:

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

DecimalFormatSymbols parameter could be omitted for case to use current locale for parsing

like image 141
Marek Gregor Avatar answered Oct 10 '22 22:10

Marek Gregor


You could try :

    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(...) {
    }

There might be a better solution though

like image 36
TheWalkingCube Avatar answered Oct 10 '22 22:10

TheWalkingCube


Not same API, but worth trying

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

outputs:

-1000001 and 1000001

like image 42
DayaMoon Avatar answered Oct 10 '22 21:10

DayaMoon