String formatting on numbers is very useful for creating readable output. This can be done through the use of the number object’s ToString() method.
A common practice is printing out mathematical operations with the use of the ToString() method on the double object. What usually happens is the printing of a long string containing all the decimal places existing in the double. This sometimes makes output cluttered and hard to read. Luckily, C# has a robust set of string formatting options available to make the string more comprehendible.
Here is a list of common formatting options available in the ToString() method:
The corresponding output is as follows:
For custom formatting you can use the following:
For more information on general string formatting this guide may be of use. Many other resources can be found online through a Google search as well.