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,689 questions

55,441 answers

573 users

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

1 Answer

0 votes
# 
#     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"
#
def format_decimal_with_zeros(num, width, decimals)

    # Split into integer and fractional parts
    integer_part = num.to_i
    fractional_part = num - integer_part

    # Format integer part with leading zeros
    int_str = sprintf("%0#{width}d", integer_part)

    # Format fractional part (starts with "0.xxx")
    frac_str = sprintf("%.#{decimals}f", fractional_part)

    # Remove the leading "0" before the decimal point
    int_str + frac_str[1..]
end

num = 3.14159

result = format_decimal_with_zeros(num, 5, 5)

puts "Original number: #{sprintf('%.5f', num)}"
puts "Formatted string: #{result}"



=begin
run:
             
Original number: 3.14159
Formatted string: 00003.14159
         
=end

 



answered Apr 26 by avibootz

Related questions

...