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

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

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

Example:

Decimal value: 193.45

The result should be: 0000019345

Decimal value: 245

The result should be: 0000024500

I know what I can use string.format("{format here}", value)or .ToString("format here"), but I don’t know which string format to use.

+4
source share
4 answers

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

, NumberFormatInfo . :

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

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

:

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

string. , , .

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

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

, , , , , :

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");
    }
}

, , .

0

All Articles