Ad space (banner)
#๏ธโƒฃC# Lessons
Lesson 49 / 68

Formatting Numbers (Padding Digits, Decimal Places)

In this lesson you will learn how to format numbers in C#, lining up digits and decimal places so values display neatly. This is for anyone searching for "C# ToString format how to use".

.ToString("F2") fixes the number of decimal places, and .ToString("D3") pads the front with zeros to a fixed width. Both are handy for displaying amounts or generating numbered file names.

The sample code turns 1234.5 into "1234.50 dollars" with two decimal places via price.ToString("F2"), and turns 7 into the zero-padded "007" via num.ToString("D3"). Notice the difference between the F and D format specifiers.

A common stumbling block for beginners is the sheer number of format specifiers. Knowing these format strings lets you respond quickly to all sorts of display requirements.

In real-world development, specifying a culture also gives you display that follows each country's conventions, such as thousands separators.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C# directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)