Numbers

Contents
Integers
Floats
Basic math
To_i to_f round

Integers

Integers are whole numbers: counts, ages, and indexes. They can be positive, negative, or zero, and Ruby handles very large integers without extra effort.

Underscores may split long digits into groups of three. They are ignored by the interpreter and exist only for human eyes:

seats = 42 crowd = 1_000_000 puts seats # prints 42 puts crowd # prints 1000000

Floats

Floats are numbers with a decimal point: prices, weights, and averages. Any number written with a dot becomes a float, even when the fraction is zero.

price = 9.99 whole = 3.0 puts price # prints 9.99 puts whole # prints 3.0

Basic math

The usual operators work as expected: plus, minus, multiply, divide, remainder, and power. Watch out for one detail: dividing two integers drops the fraction and returns an integer.

2 + 3 # => 5 2 ** 10 # => 1024 7 / 2 # => 3 7.0 / 2 # => 3.5

When at least one side is a float, the result is a float. That is the simplest way to keep the decimal part of a division.

To_i to_f round

Input from users and files arrives as strings, so Ruby offers small converters with clear names. to_i turns a string into an integer, to_f into a float, and round trims a float to the nearest whole number.

"42".to_i # => 42 "3.5".to_f # => 3.5 3.7.round # => 4 3.2.round # => 3

Next: Strings

Article author: Arthur Isaev

Related articles
Ruby
Ruby course: zero to hero in 50 lessons
What is Ruby and where it runs
Install Ruby and check the version
irb: the interactive shell
Your first Ruby script
Variables
Numbers
Strings
Symbols
Truthiness: only false and nil
Conditions
Loops
Arrays
Hashes
Ranges
Methods
Blocks, procs, lambdas
String tools
Files and IO
Exceptions
Modules and mixins
Classes and objects
Inheritance
Enumerables
Duck typing and core idioms
Gems and Bundler
Testing with Minitest
Debugging
Encodings
Time and date
JSON and YAML
HTTP clients
Sockets
REST APIs
puts, print and p
Metaprogramming
Enumerators
Pattern matching
Arguments: splats and kwargs
Rake tasks
Environment and CLI
Logging
CSV
ERB templates
WEBrick server
Rails in one lesson
Capstone: todo CLI
Capstone: JSON API
Performance
Modern Ruby tour
Hero roadmap: the whole course on one page
Install Ruby on Windows 11
Install Ruby on Ubuntu
Install Ruby on Rocky Linux
Install Ruby on macOS
Install Ruby on FreeBSD
Ruby in Docker
Threads and fibers
Banner image

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: