C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Substitution: In the format pattern, we see the marker {0}, which means the second argument is to be inserted there.
And: The marker {1:0.0} means the third argument is to be inserted there, with one digit after the decimal place.
Finally: The marker {2:yyyy} means the fourth argument is to be inserted there, with only the year digits being added.
VB.NET program that uses format String
Module Module1
Sub Main()
Dim name As String = "The Dev Codes"
Dim number As Integer = 10000
Dim day As DateTime = New DateTime(2007, 11, 1)
' Format with String.Format.
Dim result As String =
String.Format("{0}: {1:0.0} - {2:yyyy}",
name, number, day)
' Write result.
Console.WriteLine(result)
End Sub
End Module
Output
The Dev Codes: 10000.0 - 2007
Caution: If you pass a 100-based percentage figure to String.Format, you will get a percentage that is larger than you might want.
VB.NET program that uses percentage String
Module Module1
Sub Main()
' Convert Double to percentage String.
Dim ratio As Double = 0.73
Dim result As String =
String.Format("String = {0:0.0%}", ratio)
Console.WriteLine(result)
End Sub
End Module
Output
String = 73.0%
And: With the marker {1,10}, the string is padded to ten characters with the spaces on the left.
Thus: You can see the types of values inserted in the substitution markers can vary.
VB.NET program that uses padding String
Module Module1
Sub Main()
' Format String.
Dim format As String = "{0,-10} {1,10}"
' Construct lines.
Dim line1 As String = String.Format(format, 100, 5)
Dim line2 As String = String.Format(format, "Carrot", "Giraffe")
Dim line3 As String = String.Format(format, True, False)
' Print them.
Console.WriteLine(line1)
Console.WriteLine(line2)
Console.WriteLine(line3)
End Sub
End Module
Output
100 5
Carrot Giraffe
True False
Note: The substitution markers, such as {0:0000}, can be changed to just 0000. The argument index is omitted.
Note 2: This is a simpler function call. This simplicity will be reflected in the program's performance.
VB.NET program that uses ToString
Module Module1
Sub Main()
Dim value As Integer = 123
Dim a As String = String.Format("{0:0000}", value)
Dim b As String = value.ToString("0000")
' Print results. They are equal.
Console.WriteLine(a)
Console.WriteLine(b)
End Sub
End Module
Output
0123
0123
And: You can call the Console.WriteLine function with the same arguments as String.Format.
Console