How to convert a decimal to integer in Ruby

1 Answer

0 votes
require 'bigdecimal'
require 'bigdecimal/util'

=begin
    ============================================================
    Convert a decimal-like value to an Integer in Ruby.

    This program demonstrates:
      • Conversion using round, which rounds to the nearest integer.
      • Conversion using to_i, which truncates toward zero.
      • Conversion using BigDecimal for precise decimal arithmetic.
      • A helper method that prints all conversion styles.

    Notes:
      • Ruby does not have a separate "long" type; Integer expands as needed.
      • round returns an Integer.
      • to_i removes the fractional part.
      • BigDecimal#to_i also truncates.
    ============================================================
=end

# Rounds a Float to an Integer
def convert_decimal_to_integer(value)
  value.round
end

# Truncates a Float to an Integer
def cast_decimal_to_integer(value)
  value.to_i
end

# Converts BigDecimal using truncation
def convert_bigdecimal_to_integer(value)
  value.to_i
end

# Prints both conversion styles for Float
def show_float_conversions(value)
  puts "Input decimal (Float): #{value}"

  rounded   = convert_decimal_to_integer(value)
  truncated = cast_decimal_to_integer(value)

  puts "Rounded (round): #{rounded}"
  puts "Truncated (to_i): #{truncated}"
  puts
end

# Prints conversion styles for BigDecimal
def show_bigdecimal_conversions(value)
  puts "Input decimal (BigDecimal): #{value}"

  truncated = convert_bigdecimal_to_integer(value)
  puts "Truncated (to_i): #{truncated}"

  puts
end

# Main
show_float_conversions(12.7)
show_float_conversions(12.3)
show_float_conversions(-5.8)
show_float_conversions(42.0)

show_bigdecimal_conversions(BigDecimal("12.7"))
show_bigdecimal_conversions(BigDecimal("42"))
show_bigdecimal_conversions(BigDecimal("-5.8"))



=begin
run:

Input decimal (Float): 12.7
Rounded (round): 13
Truncated (to_i): 12

Input decimal (Float): 12.3
Rounded (round): 12
Truncated (to_i): 12

Input decimal (Float): -5.8
Rounded (round): -6
Truncated (to_i): -5

Input decimal (Float): 42.0
Rounded (round): 42
Truncated (to_i): 42

Input decimal (BigDecimal): 0.127e2
Truncated (to_i): 12

Input decimal (BigDecimal): 0.42e2
Truncated (to_i): 42

Input decimal (BigDecimal): -0.58e1
Truncated (to_i): -5

=end

 



answered Aug 6 by avibootz
...