0

I am attempting to write out to a fixed format text file and am having some trouble formatting the numbers properly. It needs to be padded with leading zeros and an implied decimal.

Example:

43.80

The output would need to be:

0000004380

So far, I have attempted to convert the double to a string, replace the decimal, and then pad with "0".

((amount.ToString()).Replace(".","")).PadLeft(10, '0')

The problem with this is when the number ends with zeros. The above example comes out as:

0000000438

Any suggestions?

Andrew Spencer
  • 15,164
  • 4
  • 29
  • 48
Joel S.
  • 105
  • 2
  • 6

4 Answers4

1
decimal value = 34.80M;
int intVal = (int)(value * 100);
return intVal.ToString("0000000000");
Jon
  • 3,230
  • 1
  • 16
  • 28
0

You could try:

((string.Format("{0:0.00}", amount)).Replace(".","")).PadLeft(10, '0')

That way you don't lose the 2nd decimal place when the value is 0.

CDurand
  • 54
  • 4
0

You can pass a .ToString() format string in as described in this article: https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx

Does the incoming value always have two decimal places? If so, you could multiply by 100 to get rid of the decimal, and then to .ToString("D10")

(Int)(43.80 * 100).ToString("D10")

Dave Smash
  • 2,941
  • 1
  • 18
  • 38
0

This should do the job : $"{(int)(amount * 100):D010}"

Xiaoy312
  • 14,292
  • 1
  • 32
  • 44