Strings
Various Strings Tips
String.Format
String.Format is one option to insert the value of an object, variable, or expression into another string. For example, you can insert the value of a Decimal value into a string to display it to the user as a single string:
String.Format("The current price is {0} per ounce.",pricePerOunce);
And you can control that value's formatting:
String.Format("The current price is {0:C2} per ounce.", pricePerOunce);
// Result if current culture is en-US: "The current price is $17.36 per ounce."
$ String Interpolation
The $ special character identifies a string literal as an interpolated string.
Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now.");
The syntax is as follows:
{<interpolationExpression>[,<alignment>][:<formatSpecifier>]}
Like for example:
Console.WriteLine($"|{"Left",-7}|{"Right",7}|");
string name = "Horace";
int age = 34;
// use {{ }} to generate { } in string.
Console.WriteLine($"He asked, \"Is your name {name}?\", but didn't wait for a reply :-{{");
Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old.");
// Expected output is:
// He asked, "Is your name Horace?", but didn't wait for a reply :-{
// Horace is 34 years old.
Number Format Specifiers:
| Specifier | Description | Example |
|---|---|---|
| d D f F g G ... | date (full list) | Thursday, 10 April 2008 06:30 |
| C | currency | |
| D | decimal | |
| E | fixed-point (float) | |
| G | general | |
| P | percentage | |
| X x | hexadecimal |
Formatting numbers
In formatting numbers you can use 0 as a mandatory place and # as an optional place:
// just two decimal places
float temp = 123.4567;
Console.WriteLine($"{temp:0.##}"); // "123.46"
Console.WriteLine($"{temp:0.0#}"); // "123.41"
Console.WriteLine($"{temp:0.0}"); // "123.4"
Newline
You can add a new line with
result.text=$"This is a {Environment.NewLine} comment!";