-2

I have some numbers that are represented as Strings. Some of them are formatted like this, "12,309". I need to change them to ints, sum them, and then change them back to strings with commas in the appropriate place. How would I go about doing this?

Saliceran
  • 330
  • 1
  • 7
  • 26
  • 1
    Take a look at these two SO questions: [String to integer][1] [Integer to string][2] [1]: http://stackoverflow.com/questions/1097332/convert-a-string-to-number-java [2]: http://stackoverflow.com/questions/7070209/converting-integer-to-string-with-comma-for-thousands – Rob Watts Apr 09 '13 at 18:20
  • I've tried Integer.valueOf() but that doesn't work because it doesn't get rid of the comma. I've also tried to use NumberFormat but I'm not really sure how that works. – Saliceran Apr 09 '13 at 18:21
  • @TGMCians, good point (about my deleted answer), others have covered this to a much better depth. – Jason Sperske Apr 09 '13 at 18:23

2 Answers2

3

Use the DecimalFormat class to specify a format with commas. Use the parse method to parse a String into a Number, and the format method to convert it back into a String with commas.

A format string "#,###" should be sufficient to represent comma-separated numbers such as 1,234,567.

rgettman
  • 176,041
  • 30
  • 275
  • 357
  • This is the right tool for the job. OP should take a look at [the Numbers and Currencies tutorial](http://docs.oracle.com/javase/tutorial/i18n/format/numberintro.html). – Ted Hopp Apr 09 '13 at 18:26
  • This is a much neater solution than the one I gave using regex, thanks rgettman! – phcoding Apr 09 '13 at 18:57
0

Using regular expressions for a space delimited string this would work

String regex = "(?<=[\\d])(,)(?=[\\d])";
Pattern p = Pattern.compile(regex);

String str = "12,000 1,000 42";

int currentInt = 0;
int sum = 0; 
String currentStr = "";

for(int i = 0; i < commaDelimitedNumbers.length; i++){

    currentStr = commaDelimitedNumbers[i];

    Matcher m = p.matcher(currentStr);

    currentStr = m.replaceAll("");

    currentInt = Integer.parseInt(currentStr);

    sum  += currentInt;
}

System.out.println(sum);
phcoding
  • 608
  • 4
  • 16