Home > Back-end >  Format eleven digit number to string
Format eleven digit number to string

Time:08-24

I have number eleven digit number from my DB: 12345678910 I need to get this number in the following format: 123-456-789-10 How i can get it with standart Java?

CodePudding user response:

You could use regex after converting your number to string:

long number = 12345678910L;

String str = String.join("-", String.valueOf(number).split("(?<=\\G...)"));
System.out.println(str);

CodePudding user response:

You can use a StringBuilder:

    long number = 12345678910L;
    String stringNumber = new StringBuilder(number   "")
            .insert(3, '-')
            .insert(7, '-')
            .insert(11, '-')
            .toString();

CodePudding user response:

That number is way too long to be an Integer. It depends on the data type you pull from the database. Use a long instead.

    long yourInteger = 12345678910L;
    StringBuilder stringBuilder = new StringBuilder();
    String s = Long.toString(yourInteger);

    for (int i = 0; i < s.length(); i = i   3) {
        if (s.length() - i > 3) {
            String subString = s.substring(i, i   3);
            stringBuilder.append(subString);
            stringBuilder.append("-");
        }
    }

    stringBuilder.append(s.substring(s.length() - 2));

    System.out.println(stringBuilder.toString());

CodePudding user response:

11 digits might overflow an int so use a long.

long n = resultSet.getLong(...);

String formatN(long n) {
    if (n < 0) {
        throw new IllegalArgumentException("Illegal "   n);
    }
    String d = String.format("1d", n);
    if (d.length() > 11) {
        throw new IllegalArgumentException("Illegal "   n);
    }
    return d.substring(0, 3)   "-"   d.substring(3, 6)
          "-"   d.substring(6, 9)   "-"   d.substring(9);
}

CodePudding user response:

How about like this. Use String.replaceAll.

  • Convert the long to a String
  • Replace every 3 digits with those digits followed by a -
  • $0- is the back reference to the string matched by the regex.
long value = 12345678910L;
String val = Long.toString(value).replaceAll("\\d\\d\\d","$0-");
System.out.println(val);

prints

123-456-789-10

This easily lends itself to a lambda


Function<Long, String> format = v->Long.toString(v).replaceAll("\\d\\d\\d","$0-");
String result = format.apply(value);

Note: If the number is a already a String or can be retrieved as one, you can forgo the Long.toString() conversion.

  • Related