mherr
mherr

Reputation: 378

String.Format() - How to use a variable that contains your formatting?

In vb.net, I am attempting to format a string into a formatted Phone Number where the formatting is read in from a database variable.

A phone number like "5555555555" will get nicely formated into "(555) 555-5555" if the string is formatted in this fashion:

String.Format("{0:(###) ###-####}", Long.Parse(PhoneNum))

However, the "(###) ###-####" string is stored in a database, to maintain a central formatting choice for phone numbers in a theoretical system.

Does anyone know how I can substitute this hardcoded formatting for one with a variable? I am trying something like:

Dim phoneFormat as String = <~read in the String format from DB~>
String.Format("{0:" & phoneFormat.ToString & "}", Long.Parse(PhoneNum)))

Unfortunately however, this only returns the string itself. I am presented with "(###) ###-####".

Upvotes: 0

Views: 2683

Answers (1)

djv
djv

Reputation: 15774

Object.ToString is probably simpler, but you can still use String.Format. Here are these two methods

Dim phoneNum = "1234567890"
Dim phoneFormat = "(###) ###-####"
' simpler version using Long.ToString
Dim formattedPhoneNumber1 = Long.Parse(phoneNum).ToString(phoneFormat)
' your original attempt using String.Format
Dim formattedPhoneNumber2 = String.Format("{0:" & phoneFormat & "}", Long.Parse(phoneNum))
' cleaner version using String.Format with traditional interpolation and $ interpolation
Dim formattedPhoneNumber3 = String.Format($"{{0:{phoneFormat}}}", CLng(phoneNum))
Console.WriteLine(formattedPhoneNumber1)
Console.WriteLine(formattedPhoneNumber2)
Console.WriteLine(formattedPhoneNumber3)
Console.ReadLine()

(123) 456-7890
(123) 456-7890
(123) 456-7890

I think what you were probably not sending the Long into the function, rather the string (by the way why is the number 5555555555 being stored as a string in the first place?). You need to include Long.Parse() otherwise the #s in your format won't know what to operate on.

Upvotes: 2

Related Questions