Designate a negative number with parentheses

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

Example:

(123,456) = -123456

123,456 = 123456

I used the NumberFormat class, but only converts only positive numbers, 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 up to 123456

I could not parse your string!

+7
java parsing
source share
11 answers

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

May be a better solution though

+3
source share

A simple trick without special parsing logic:

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

DecimalFormatSymbols parameter can be omitted for the case of using the current locale for parsing

+6
source share

Not the same API, but worth a try

  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

+4
source share

I have another solution:

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

This is an atypical solution, even if there is a duplicate message, I think this answer is worth it :)

+2
source share

This should work:

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

The output will be:

negative: -123456
positive: 123456

+2
source share

Here I am trying to change a string to an integer and then return to an integer in a string.

Double slashes ('\\') are used to escape a special character, if they are used in several cases.

Here is the complete code snippet: Tested and Executed.

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

Now you see the expected results as indicated.

+2
source share
 private int getIntValue(String numberToParse) { if (numberToParse.contains("(")) { numberToParse = numberToParse.replaceAll("[(),]", ""); return Integer.valueOf(numberToParse) * -1; } else { numberToParse = numberToParse.replaceAll("[,]", ""); return Integer.valueOf(numberToParse); } } 
+2
source share

If you are sure that only lines with the specified format appear, then why not just replace the leading "(" minus sign and final ")" with nothing before parsing, as in:

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

You can try it like this:

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

OUTPUT:

  123456 -123456 
+1
source share

You can get what you need:

  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()); } 
0
source share

Try the following:

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

This will check if the string contains "(". If so, it will remove all characters ('and') ', convert the string to an integer and make the value negative. Otherwise, it will remove the character', '' and parse the integer, which is positive.

0
source share

All Articles