What’s the right way to represent phone numbers?

Use String. Aside from anything else, you won’t be able to store leading zeroes if you use integers. You definitely shouldn’t use int (too small) float or double (too much risk of data loss – see below); 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.

In terms of the “data loss” mentioned above for float and doublefloat definitely doesn’t have enough precision; double could work if you’re happy that you’ll never need more than 16 digits (a couple fewer than you get with long) but you would need to be very, very careful that anywhere you convert the value back from double to string, you got the exact value. Many formatting conversions will give you an approximation which may be accurate to, say, 10 significant digits – but you’d want an exact integer. Basically, using floating point for phone numbers is a fundamentally bad idea. If you have to use a fixed-width numeric type, use a long, but ideally, avoid it entirely.

Leave a Comment