VAAA
VAAA

Reputation: 15049

How to format decimal with leading zeros and without a separator?

I have a requirement to format a decimal value into a 8 positions where the last 2 digits are reserved for decimal values.

The format should be: 00000000 (where the last 2 zeros are for decimal value).

Example:

Decimal Value: 193.45

The result should be: 0000019345

Decimal Value: 245

The result should be: 0000024500

I know that I can use string.format("{format here}", value) or .ToString("format here") but dont know what string format to use.

Upvotes: 4

Views: 5248

Answers (4)

Brett Wolfington
Brett Wolfington

Reputation: 6627

Have a look at the MSDN documentation for Custom Numeric Format Strings.

It would likely be possible to define a custom NumberFormatInfo to print strings in this format. However, a much easier way to accomplish this would be either of the following options:

(value * 100).ToString("00000000");

string.Format("{0:00000000}", value * 100);

Upvotes: 5

Matthew Haugen
Matthew Haugen

Reputation: 13296

I would probably just do string manipulation. I'm sure there is a format designator, but that seems easier.

string ret = (decimalValue * 100).ToString();

return ret.PadLeft(8, '0');

Upvotes: 0

allonym
allonym

Reputation: 1418

Try this:

decimalValue.ToString("00000000.00").Replace(".", "");

Upvotes: 0

mtmk
mtmk

Reputation: 6326

Just for fun, playing with the decimal type I found that by accessing its binary representation I was able to change the scale then format it to your requirements:

public class Program
{
    static void Main()
    {
        decimal[] ds = { 193.45m, 245.00m };
        foreach (decimal d in ds)
        {
            Console.WriteLine(Format8(d));
        }
    }

    static string Format8(decimal d)
    {
        int[] parts = decimal.GetBits(d);
        bool sign = (parts[3] & 0x80000000) != 0;

        byte scale = (byte)((parts[3] >> 16) & 0x7F);
        Debug.Assert(scale == 2);
        scale = 0; // alter scale to remove the point

        return new decimal(parts[0], parts[1], parts[2], sign, scale)
            .ToString("00000000");
    }
}

One caveat is that if you have any data without two decimal points this approach would fail.

Upvotes: 0

Related Questions