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!
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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With