Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,690 questions

55,449 answers

573 users

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 Apr 26 by avibootz

Related questions

...