0

Below code will return "-1-2346", how to return "123-46"? we save phone number in database as varchar(20), and always 10 digitalis. asp page just need display whatever it is.

var phoneNumber = 12346;
var phoneString = String.Format("{0:###-###-####}",12346);
GrahamTheDev
  • 22,724
  • 2
  • 32
  • 64
seagull
  • 237
  • 1
  • 7
  • 19

1 Answers1

1

You can create custom format provider

public class TelephoneFormatter : IFormatProvider, ICustomFormatter
    {
        public object GetFormat(Type formatType)
        {
            return formatType == typeof(ICustomFormatter) ? this : null;
        }

        public string Format(string format, object arg, IFormatProvider formatProvider)
        {
            var numericString = arg.ToString();

            if (format != "###-###-####") 
                return String.Format(format, arg);

            if (numericString.Length <= 3)
                return numericString;
            if (numericString.Length <= 6)
                return numericString.Substring(0, 3) + "-" + numericString.Substring(3, numericString.Length - 3);
            if (numericString.Length <= 10)
                return numericString.Substring(0, 3) + "-" +
                       numericString.Substring(3, 3) + "-" + numericString.Substring(4, numericString.Length - 6);

            throw new FormatException(
                string.Format("'{0}' cannot be used to format {1}.",
                    format, arg));
        }
    }

After this you can use it

public static void Test()
    {
        Debug.Print(String.Format(new TelephoneFormatter(), "{0:###-###-####}", 0));
        Debug.Print(String.Format(new TelephoneFormatter(), "{0:###-###-####}", 911));
        Debug.Print(String.Format(new TelephoneFormatter(), "{0:###-###-####}", 12346));
        Debug.Print(String.Format(new TelephoneFormatter(), "{0:###-###-####}", 8490216));
        Debug.Print(String.Format(new TelephoneFormatter(), "{0:###-###-####}", 4257884748));
    }

I hope it will help you.

Result

0
911
123-46
849-021-2
425-788-8847
Baximilian
  • 885
  • 7
  • 25