What is the best way to zero pad a numeric field?

  • Thread starter Thread starter Bill
  • Start date Start date
B

Bill

I have a decimal value that needs to be written to a file for input into a
COBOL program. The format of the COBOL input value is 9(9)V99. IOW, this is
an eleven byte field with an implied decimal. Thus a decimal value of 109.52
would need to be formatted as 00000010900.

What is the most efficient way of doing this?
 
OK... this works, but is really ugly:

private void WriteDataSet()
{
decimal d = 109.25m;
Console.WriteLine("D11 format: {0:D11}",
Convert.ToInt32(d.ToString().Replace(".","")));
}

RESULT: 00000010925

Is there a more elegant way to do this?
 
Bill said:
OK... this works, but is really ugly:

private void WriteDataSet()
{
decimal d = 109.25m;
Console.WriteLine("D11 format: {0:D11}",
Convert.ToInt32(d.ToString().Replace(".","")));
}

RESULT: 00000010925

Is there a more elegant way to do this?

Multiplying by 100 is more elegant than the convert to
string/replace/convert to int hack.

You should look into creating a NumberFormatInfo and setting the
NumberDecimalSeparator property to string.Empty. Then you just format like
this:

Console.WriteLine(d.ToString("000000000.00", myNumberFormatInfo);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top