How Do Format a Phone Number as a String in Java

How do format a phone number as a String in Java?

This is how I ended up doing it:

private String printPhone(Long phoneNum) {
StringBuilder sb = new StringBuilder(15);
StringBuilder temp = new StringBuilder(phoneNum.toString());

while (temp.length() < 10)
temp.insert(0, "0");

char[] chars = temp.toString().toCharArray();

sb.append("(");
for (int i = 0; i < chars.length; i++) {
if (i == 3)
sb.append(") ");
else if (i == 6)
sb.append("-");
sb.append(chars[i]);
}

return sb.toString();
}

I understand that this does not support international numbers, but I'm not writing a "real" application so I'm not concerned about that. I only accept a 10 character long as a phone number. I just wanted to print it with some formatting.

Thanks for the responses.

How to format a phone number in a textfield

TextFormatter is definitely the way to go. What you need to build is the filter component for the TextFormatter. Basically, you can think of this as a keystroke processor (that handles mouse actions as well), where all of the low-level stuff has been handled for you. You get a TextFormatter.Change object passed to you, and you can see how that change will impact the value in the field, and then modify it, suppress it, or let it pass through.

So all of the formatting happens instantly, right in the TextField as you type.

I built one to handle North American style phone numbers, because it's a little more interesting than the European style since it has brackets and dashes. But you can adapt it.

The approach I took was to strip all of the formatting characters out of the string, then reformat it from scratch each time a change was made. This seems easier than trying to fiddle with it character by character. The only tricky part was hitting <BackSpace> over a "-" or ")", where I assumed that you'd want to delete the number in front of the special character. It might make more sense to just move the caret to the left of the special character:

public class PhoneNumberFilter implements UnaryOperator<TextFormatter.Change> {

@Override
public TextFormatter.Change apply(TextFormatter.Change change) {
if (change.isContentChange()) {
handleBackspaceOverSpecialCharacter(change);
if (change.getText().matches("[0-9]*")) {
int originalNewTextLength = change.getControlNewText().length();
change.setText(formatNumber(change.getControlNewText()));
change.setRange(0, change.getControlText().length());
int caretOffset = change.getControlNewText().length() - originalNewTextLength;
change.setCaretPosition(change.getCaretPosition() + caretOffset);
change.setAnchor(change.getAnchor() + caretOffset);
return change;
} else {
return null;
}
}
return change;
}

private void handleBackspaceOverSpecialCharacter(TextFormatter.Change change) {
if (change.isDeleted() && (change.getSelection().getLength() == 0)) {
if (!Character.isDigit(change.getControlText().charAt(change.getRangeStart()))) {
if (change.getRangeStart() > 0) {
change.setRange(change.getRangeStart() - 1, change.getRangeEnd() - 1);
}
}
}
}

private String formatNumber(String numbers) {
numbers = numbers.replaceAll("[^\\d]", "");
numbers = numbers.substring(0, Math.min(10, numbers.length()));
if (numbers.length() == 0) {
return "";
}
if (numbers.length() < 4) {
return "(" + numbers;
}
if (numbers.length() < 7) {
return numbers.replaceFirst("(\\d{3})(\\d+)", "($1)$2");
}
return numbers.replaceFirst("(\\d{3})(\\d{3})(\\d+)", "($1)$2-$3");
}

}

Here's a little test application. You can see that the converter is just the "out of the box" default converter, since it's just a string composed of mostly numbers:

public class PhoneNumberTest extends Application {

public static void main(String[] args) {
launch(args);
}

@Override
public void start(Stage primaryStage) {
TextField textField = new TextField();
TextFormatter<String> textFormatter = new TextFormatter(new DefaultStringConverter(), "", new PhoneNumberFilter());
textField.setTextFormatter(textFormatter);
Scene scene = new Scene(new VBox(textField), 300, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
}

Java: Format a string as a telephone number

String.format("(%s) %s-%s", number.substring(0, 3), number.substring(3, 6), 
number.substring(6, 10));

Java phone number format API

You could write your own (for US phone # format):

  • Strip any non-numeric characters from the string
  • Check that the remaining string is ten characters long
  • Put parentheses around the first three characters and a dash between the sixth and seventh character.
  • Prepend "+1 " to the string


Update:

Google recently released libphonenumber for parsing, formatting, storing and validating international phone numbers.

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 double - float 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.

How to format a converted phone number in java?

Adding below mentioned in your main method will resolve you issue.

long subString = (convertedPhoneNumber%10000000);    
String updatedStringPhone = initialPhoneNumber.substring(0,6)+subString/10000+"-"+subString%10000;

Overall method will be:

public static void main(String[] args) 
{
System.out.println ("Enter phone number:");
Scanner scanInput = new Scanner (System.in);
String initialPhoneNumber;
initialPhoneNumber = scanInput.nextLine ();

initialPhoneNumber = initialPhoneNumber.toUpperCase();
long convertedPhoneNumber = phoneNumber (initialPhoneNumber);
long subString = (convertedPhoneNumber%10000000);
String updatedStringPhone = initialPhoneNumber.substring(0,6)+subString/10000+"-"+subString%10000;
System.out.println("Updated: "+updatedStringPhone);
System.out.println ("Converted: " + convertedPhoneNumber);

}

Description:
Converted to strings and added the following strings. For Example

"1-800-"

"356"

"-"

"9377"

how to extract a phone number for a string using regular expression?

The following code will check for the phone number in the string you mention and print it:

String str = "This is 1 test 123-456-7890";

Pattern pattern = Pattern.compile("\\d{3}-\\d{3}-\\d{4}");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
System.out.println(matcher.group(0));
}

But, as pointed out in other answers, many phone numbers (especially not international ones) will not match the pattern.



Related Topics



Leave a reply



Submit