Float
Float.new, Float() Returns:
Float · Updated March 13, 2026 · Core Classes numbers floating-point numeric precision
The Float class represents floating-point numbers in Ruby, following the IEEE 754 double-precision format. Floats are used when you need decimal numbers with fractional parts.
Creating Floats
# Direct assignment
x = 3.14159
y = -2.5
z = 1.0
# Using Float() conversion
Float(42) # => 42.0
Float("3.14") # => 3.14
# From integers
100.to_f # => 100.0
# Scientific notation
1e5 # => 100000.0
1.5e-3 # => 0.0015
Float Methods
# Infinite and NaN checks
(1.0 / 0).infinite? # => 1 (positive infinity)
(-1.0 / 0).infinite? # => -1 (negative infinity)
(0.0 / 0).nan? # => true (Not a Number)
# Rounding
3.14159.round(2) # => 3.14
3.14159.floor # => 3
3.14159.ceil # => 4
# Conversion
3.14159.to_i # => 3 (truncates)
3.14159.to_s # => "3.14159"
Precision Considerations
# Floating-point precision issues
0.1 + 0.2 # => 0.30000000000000004
# Use BigDecimal for precision
require 'bigdecimal'
BigDecimal("0.1") + BigDecimal("0.2")
# => 0.3 (exact)
# Comparing floats
a = 0.1 + 0.2
b = 0.3
(a - b).abs < 0.0001 # => true (tolerance comparison)
Practical Examples
Mathematical Operations
# Basic math
2.5 + 1.5 # => 4.0
3.0 * 4.0 # => 12.0
10.0 / 3.0 # => 3.3333333333333335
5.0 ** 2 # => 25.0
# Using Math module
Math.sqrt(16.0) # => 4.0
Math.sin(Math::PI / 2) # => 1.0
Math.log(Math::E) # => 1.0
Working with Currency (use BigDecimal in production)
# Simple price calculations (warning: precision issues!)
price = 19.99
tax = price * 0.08
total = price + tax
# => 21.5892
# Rounding for display
puts "Total: $#{total.round(2)}" # => Total: $21.59
Temperature Conversion
def celsius_to_fahrenheit(c)
c * 9.0 / 5 + 32
end
def fahrenheit_to_celsius(f)
(f - 32) * 5.0 / 9
end
celsius_to_fahrenheit(100) # => 212.0
fahrenheit_to_celsius(32) # => 0.0
Division Behavior
# Integer vs float division
5 / 2 # => 2 (integer division)
5.0 / 2 # => 2.5
5 / 2.0 # => 2.5
5.0 / 2.0 # => 2.5
Special Values
# Infinity
Float::INFINITY # => Infinity
1.0 / 0 # => Infinity
Float::INFINITY > Float::INFINITY # => false
# Negative infinity
-1.0 / 0 # => -Infinity
# Not a Number (NaN)
0.0 / 0 # => NaN
Math.sqrt(-1) # => NaN
Floats are essential for scientific computing, graphics, and any application requiring decimal math, but be aware of their precision limitations.