Search code examples
c#.netformattingfixed-width

Left-pad a floating point number without losing trailing zeros after decimal point


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?


Solution

  • decimal value = 34.80M;
    int intVal = (int)(value * 100);
    return intVal.ToString("0000000000");