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

Create your online store today with Shopify

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

Disclosure: My content contains affiliate links.

43,563 questions

56,781 answers

573 users

How to get the Nth digit after the decimal point of a floating-point number in Ruby

1 Answer

0 votes
# Returns the Nth digit after the decimal point.
#
# Examples:
#   get_nth_decimal_digit(123.456789, 1) # => 4
#   get_nth_decimal_digit(123.456789, 2) # => 5
#   get_nth_decimal_digit(123.456789, 3) # => 6
#
# @param value [Float] The floating-point number to inspect.
# @param position [Integer] The digit position after the decimal point (1-based).
# @return [Integer] The requested digit (0-9), or 0 if it does not exist.
def get_nth_decimal_digit(value, position)
  raise ArgumentError, "Position must be a positive integer" if position < 1

  # Work with positive values only.
  value = value.abs

  # Convert the number to a string with fixed precision.
  number_str = format("%.15f", value)

  # Find the decimal point.
  decimal_pos = number_str.index(".")

  return 0 if decimal_pos.nil?

  # Calculate the index of the requested digit.
  digit_index = decimal_pos + position

  # Return 0 if the digit does not exist.
  return 0 if digit_index >= number_str.length

  number_str[digit_index].to_i
end

# -----------------------------------------------------------------------------
# Usage Examples
# -----------------------------------------------------------------------------

number = 123.456789

puts "Number: #{number}"
puts

(1..6).each do |position|
  puts "#{position} digit after decimal = " \
       "#{get_nth_decimal_digit(number, position)}"
end

puts
puts "Additional Examples"
puts "-------------------"

puts "123.456789, position 4 -> " \
     "#{get_nth_decimal_digit(123.456789, 4)}"

puts "-98.7654, position 2 -> " \
     "#{get_nth_decimal_digit(-98.7654, 2)}"

puts "1.2, position 5 -> " \
     "#{get_nth_decimal_digit(1.2, 5)}"



# run:
#
# Number: 123.456789
# 
# 1 digit after decimal = 4
# 2 digit after decimal = 5
# 3 digit after decimal = 6
# 4 digit after decimal = 7
# 5 digit after decimal = 8
# 6 digit after decimal = 9
# 
# Additional Examples
# -------------------
# 123.456789, position 4 -> 7
# -98.7654, position 2 -> 6
# 1.2, position 5 -> 0
# 

 



answered 20 hours ago by avibootz

Related questions

...