O'Reilly logo

Programming C# 4.0 by Jesse Liberty, Matthew Adams, Ian Griffiths

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Formatting Data for Output

So, we know how to initialize literal strings, which is terribly useful; but what about our other data? How do we display an Int32 or DateTime or whatever?

We’ve already met one way of converting any object to a string—the virtual 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:

45

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:

45.65

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.

Standard Numeric Format Strings

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.

Currency

Example 10-7 shows how we format a decimal as a currency value, using an overload of the standard ToString method.

Example 10-7. Currency format

decimal dollarAmount = 123165.4539M; string ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required