Ahmed Ghoneim
Ahmed Ghoneim

Reputation: 7067

Integer trims starting zeros

Simply,

class Program
{
    static void Main( string [ ] args )
    {
        int i = 010;

        Console.WriteLine( i );

        Console.ReadKey( );
    }
}

Output:

10

How to stop trimming leading zeros ?
Decimals have same output, strings aren't best solution too.

Upvotes: 1

Views: 118

Answers (3)

Akintunde
Akintunde

Reputation: 56

Console.WriteLine("{0:D8}", i);

Will print "i" containing at least 8 digits. Any missing digits will become leading zeroes.

Upvotes: 0

TheEvilPenguin
TheEvilPenguin

Reputation: 5682

Number types only keep track of the binary representation of the number, not the string representation you use to initialize them.

You can format it when you output it if you want a constant number of digits:

Console.WriteLine(i.ToString("D8"));

Upvotes: 3

System Down
System Down

Reputation: 6270

You need to store it in a string. Then you can cast it back to integer when you need calculations, then cast it back to string when you're done using the desired format.

Upvotes: 1

Related Questions