3

I am fairly inexperienced in Java as well as Android. I am trying to retrieve a phone number stored in one of the contacts of the android phone emulator. While I am successful to fetch it, the number has been returned in a string in a format like "(987) 654-3210". I want to convert it to integer or long. How can I do that? If I use Integer.parseInt(String number), it returns a NumberFormatException. Failed while tried using Long.valueOf(String number) too. What should I do then? I want it like "9876543210" without any braces or hyphens.

blganesh101
  • 3,647
  • 1
  • 24
  • 44
Saikat Das
  • 95
  • 1
  • 7
  • 1
    How are you going to handle phone numbers that start with a 0? or international numbers that start with a +? – John3136 Jun 27 '13 at 03:22
  • You probably want to read [*this*](http://stackoverflow.com/a/1223064/1057429) – Nir Alfasi Jun 27 '13 at 03:23
  • 2
    A phone number is not an integer, and should not be treated as such. Phone numbers, for example, might (locally) start with a 0 - mine does. As an integer, the leading 0 would be stripped. – AMADANON Inc. Jun 27 '13 at 03:24
  • 1
    You need to use regex to sanitize it rather than trying to parse it to a long or interger directly – everconfusedGuy Jun 27 '13 at 03:24
  • What *possible* use would a phone number as an `int` or `long` be? – Brian Roach Jun 27 '13 at 03:24
  • 1
    Check: [Extract digits from a string in Java](http://stackoverflow.com/questions/4030928/extract-digits-from-a-string-in-java) – Paresh Mayani Jun 27 '13 at 03:24
  • Phone numbers aren't integers. There's not really even "groups of integers"; as @AMADANONInc points out 001 isn't the same as 1. What exactly do you want to do? – seand Jun 27 '13 at 03:45
  • well I dint think of the case of international numbers I agree,but my app deals with local numbers so I dont need to consider that.@PareshMayani your link helped me a lot.Thanks – Saikat Das Jun 27 '13 at 08:17

2 Answers2

8

using the long for storing number will be better

   String str="(987) 654-3210";
   String stt=str.replaceAll("\\D+","");
   long num= Long.parseLong(stt);
   System.out.println(num);
ajduke
  • 4,991
  • 7
  • 36
  • 56
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115
6

This should be simple. You could use regex in java to do this like below

phoneStr = str.replaceAll("\\D+","");

This will delete the non digits from the string and give you only numbers. Then you can use

int number = Integer.parseInt(phoneStr);
blganesh101
  • 3,647
  • 1
  • 24
  • 44