Decimal ("D") Format Specifier In C#

Introduction

The Decimal ("D") Format Specifier is applied to number values so it is a Standard Numeric Function. This is used to convert any number into a decimal point number. If the number is negative then it gives a negative decimal number and if the number is positive then it gives a positive decimal number. This format is supported only for the integral type values. The Decimal "D" Format Specifier with a number, for example "D8", denotes that the number must contain the specified number of digints; 8 for the example. If the number has less than eight digits (then it makes it an 8 digit number) then the number will be filled with leading zeroes to give the number the specified eight digits. If the number is greater than the number of digits specified in the Format Specifier then nothing is changed in this number. Now let's see an example of this.

namespace NumericFunction

{

    class Program

    {

        static void Main(string[] args)

        {

           //define an integer value

            int value= 12345;

            //display the number

            Console.WriteLine("The number is :"+value.ToString("D"));

            //dispaly the 8 digit number          

            Console.WriteLine("After Apply decimal format specifier :"+value.ToString("D8"));

            //dispaly the 3 digit number          

            Console.WriteLine("After Apply decimal format specifier with less value :" + value.ToString("D3"));

        }

    }

}


Output

Decimal-fromat-specifier-with-positive-value.jpg

If I enter a negative number then the result will also be negative as:
 

namespace NumericFunction

{

    class Program

    {

        static void Main(string[] args)

        {

           //define an negative integer value

            int value= -12345;

            //display the number

            Console.WriteLine("The number is :"+value.ToString("D"));

            //dispaly the 8 digit number          

            Console.WriteLine("After Apply decimal format specifier :"+value.ToString("D8"));

            //dispaly the 3 digit number          

            Console.WriteLine("After Apply decimal format specifier with less value :" + value.ToString("D3"));

        }

    }

}

Output

Decimal-fromat-specifier-with-negative-number.jpg

Summary

In this article I explained how to use the Decimal Format Specifier In C#.

Up Next
    Ebook Download
    View all
    Learn
    View all