# 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
#