I'm trying to decide between storing a phone number as a string
or an int
. Any ideas?
A phone number should always be stored as a string or text and never an integer. Some phone numbers generally use hyphens and possibly parentheses. Also, you might need to indicate the country code before the phone number such as +46 5555-555555.
String (str or text) A phone number is usually stored as a string (+1-999-666-3333) but can also be stored as an integer (9996663333).
Therefore, it is highly recommended that the phone numbers are stored along with their county code to avoid data ambiguity. This will prevent data duplication and standardise your formatting. E. 164 is an international format which defines a general format for international telephone numbers.
Phone number may be internationalised, i.e. different format for different people, thus not possible with integers.
For any situation like these, think of : will I have to calculate anything with that value? If that doesn't make any sense, you should use a string. In that case, there's no logical case where you'd use the telephone number as a number, so use a string.
I recommend using a string since that gives you more flexibility when it comes to formatting and non numeric characters like extension etc.
I would suggest using String
- aside from anything else, otherwise you won't be able to store leading zeroes. You definitely shouldn't use int
(too small) float
or double
(too much risk of data loss); long
or BigInteger
could be appropriate (aside from the leading zeroes problem), but frankly I'd go with String
. That way you can also store whatever dashes or spaces the user has entered to make it easier to remember the number, if you want to.
Reference: What's the right way to represent phone numbers?
I highly recommend you use a string
for this.
If you are going to validate phone number input then you can use the regex lib's matcher
and pattern
to make sure a phone number was entered in the correct format.
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