How to get the first digit after the decimal point of a float number in Ruby

1 Answer

0 votes
#
# This program demonstrates how to extract the first digit
# after the decimal point from a floating‑point number.
#
# Approach:
# ---------
# 1. Splitting the number into integer and fractional parts with `value.divmod(1)`.
# 2. Multiply the fractional part by 10 to shift the first decimal digit.
# 3. Convert to integer with `floor` to avoid rounding surprises.
# 4. Return the digit.
#
# This keeps the logic numeric, expressive, and efficient.
#

#
# get_first_decimal_digit:
# ------------------------
# Returns the first digit after the decimal point of a float.
#
def get_first_decimal_digit(value)
  _int_part, fractional = value.abs.divmod(1.0)  # isolate fractional part
  (fractional * 10).floor                        # shift and truncate
end

#
# Example usage
#
number = 123.456
digit  = get_first_decimal_digit(number)

puts "Number: #{number}"
puts "First digit after decimal: #{digit}"


=begin
run:

Number: 123.456
First digit after decimal: 4

=end

 



answered Sep 15 by avibootz

Related questions

...