Formatting Phone Numbers in Java and Android

I needed to format numbers nicely while storing them as a raw string in my database, so I need to turn
0433333333 into 0433 333 333 and 0262195555 into (02) 6219 5555

I couldn’t find something that did this as nicely as I hoped, but this does the job if you know what format your numbers will be as I do (They are all Australian)

My searching didn’t turn up a string mask formatter apart from one in Swing (and I sure don’t want to be importing THAT into an Android project!) so splitting and adding spaces, brackets etc. using  .substring(…) was the nicest way I could think of without writing a whole library.

Make sure the number is a raw numeric string before converting:-

now the method to format your phone numbers – as noted, this is for Australian numbers, but you can change it easy enough.

I may look at creating a library later on that will do things in a nicer way.

Share this article...