How to express a decimal number as a fixed-length string with leading zeros in C#

1 Answer

0 votes
using System;

public class Program
{
    /*
        format_decimal_with_zeros
        -------------------------
        Converts a floating‑point number into a fixed‑length string with
        leading zeros on the integer part.
    
        Parameters:
            num          - the decimal number to format
            width        - total width of the integer part (zero‑padded)
            decimals     - number of digits after the decimal point
    
        Returns:
            A formatted string such as "00003.14159"
    
        Example:
            num = 3.14159, width = 5, decimals = 5
            Output → "00003.14159"
    */
    static string formatDecimalWithZeros(double num, int width, int decimals) {
        // Split into integer and fractional parts
        int integer_part = (int)Math.Truncate(num);
        double fractional_part = num - integer_part;
    
        // Format integer part with leading zeros
        string int_str = integer_part.ToString().PadLeft(width, '0');
    
        // Format fractional part (starts with "0.xxx")
        string frac_str = fractional_part.ToString("F" + decimals);
    
        // Remove the leading "0" before the decimal point
        return int_str + frac_str.Substring(1);
    }

    public static void Main(string[] args)
    {
        double num = 3.14159;

        string result = formatDecimalWithZeros(num, 5, 5);

        Console.WriteLine("Original number: " + num.ToString("F5"));
        Console.WriteLine("Formatted string: " + result);
    }
}



/*
run:
             
Original number: 3.14159
Formatted string: 00003.14159
         
*/

 



answered 19 hours ago by avibootz

Related questions

...