-3

How can I convert a string

 (1,234) 

into a number

(1234) 

using java?

Odaiah
  • 305
  • 3
  • 6

6 Answers6

6

Use DecimalFormat

DecimalFormat  format = new DecimalFormat  ("#,###");
Number aNumber = format.parse("1,234");
System.out.println(aNumber.intValue());
vels4j
  • 11,208
  • 5
  • 38
  • 63
  • 2
    If you'd add a notion of how locale can affect the decimal point, it would be a very good answer. – ppeterka Oct 10 '13 at 10:04
2

you can use NumberFormat for that

   String number = "1,234";
   NumberFormat numberFormat = NumberFormat.getInstance();
   int i = numberFormat.parse(number).intValue();
Prabhaker A
  • 8,317
  • 1
  • 18
  • 24
1

Try String.repaceAll()

String value = "1,234";
System.out.println(Integer.parseInt(value.replaceAll(",", "")));
newuser
  • 8,338
  • 2
  • 25
  • 33
0
String str = new String("1,234");
    String str1=str.replace(",", "");
    Integer.parseInt(str1);

try with the above code

output 1234

SpringLearner
  • 13,738
  • 20
  • 78
  • 116
0

String is immutable, so when you do replaceAll, you need to reassign object to string reference,

String str = new String("1,234");
str = str.replaceAll(",", "");
System.out.println(Integer.parseInt(str));

This works fine when tested.

codingenious
  • 8,385
  • 12
  • 60
  • 90
-2

If speed was a major concern you may find something like this quite fast. It beat all comers in this post.

int value(String s) {
  // Start at zero so first * 10 has no effect.
  int v = 0;
  // Work from the end of the string backwards.
  for ( int i = s.length() - 1; i >= 0; i-- ) {
    char c = s.charAt(i);
    // Ignore non-digits.
    if ( Character.isDigit(c)) {
      // Mul curent by 10 and add digit value.
      v = (v * 10) + (c - '0');
    }
  }
  return v;
}
Community
  • 1
  • 1
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
  • This seems a rather manual way of achieving the goal. Any reason this should be preferred to the more succinct answers? – Duncan Jones Oct 10 '13 at 10:37
  • @DuncanJones - It **may** be faster than all of the others if speed is a concern. Happy with a downvote or two ... it is only a route I would take if speed was critical. Added caveat. – OldCurmudgeon Oct 10 '13 at 10:46
  • FWIW, I didn't down-vote you myself - the answer looks correct. I was just interested in possible benefits. Some rather trigger happy down-voters circulating this question for some reason. – Duncan Jones Oct 10 '13 at 10:54
  • This is just reinventing of wheel and would require modifications if integer format in input string would change. OP wasn't concerned about speed. – Piro Oct 10 '13 at 12:01