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

55,473 answers

573 users

How to count the number of digits in an integer with Ruby

2 Answers

0 votes
def count_digits_string(value)
  # Convert the number to a string
  text = value.to_s

  # If negative, ignore the leading '-'
  if text.start_with?("-")
    return text.length - 1
  end

  text.length
end

number = -12345
digits = count_digits_string(number)

puts "Number: #{number}"
puts "Digit count (String method): #{digits}"


=begin
run:

Number: -12345
Digit count (String method): 5

=end

 



answered Oct 17, 2021 by avibootz
edited 1 day ago by avibootz
0 votes
def count_digits_log10(value)
  num = value.abs

  # Zero must be handled explicitly
  return 1 if num == 0

  # Use floor(log10(n)) + 1
  Math.log10(num).floor + 1
end

number = 987_654_321
digits = count_digits_log10(number)

puts "Number: #{number}"
puts "Digit count (log10 method): #{digits}"



=begin
run:

Number: 987654321
Digit count (log10 method): 9

=end

 



answered Oct 17, 2021 by avibootz
edited 1 day ago by avibootz
...