So, we know how to initialize literal strings, which is
terribly useful; but what about our other data? How do we display an
DateTime or whatever?
We’ve already met one way of converting any object to a string—the
ToString method, which
Example 10-5 uses.
Example 10-5. Converting numbers to strings with ToString
int myValue = 45; string myString = myValue.ToString(); Console.WriteLine(myString);
This will produce the output you might expect:
What if we try a
decimal? Example 10-6 shows this.
Example 10-6. Calling ToString on a decimal
decimal myValue = 45.65M; string myString = myValue.ToString(); Console.WriteLine(myString);
Again, we get the expected output:
OK, what if we have some decimals in something like an accounting ledger, and we want to format them all to line up properly, with a preceding dollar sign?
Well, there’s an overload of
ToString on each of the numeric types that takes
an additional parameter—a format string.
In most instances, we’re not dreaming up a brand-new format for our numeric strings; if we were, people probably wouldn’t understand what we meant. Consequently, the framework provides us with a whole bunch of standard numeric format strings, for everyday use. Let’s have a look at them in action.
Example 10-7 shows how we format a decimal
as a currency value, using an overload of the standard
Example 10-7. Currency format
decimal dollarAmount = 123165.4539M; string ...