Ruby supports two types of numbers:
- Integers: An integer is simply a sequence of digits, e.g., 12, 100. Or in other words, numbers without decimal points are called Integers. In Ruby, Integers are object of class Fixnum(32 or 64 bits) or Bignum(used for bigger numbers).
- Floating-point numbers: Numbers with decimal points are usually called floats, e.g., 1.2, 10.0. The floating-point numbers are object of class Float.
Note: Underscore can be used to separate a thousand places e.g: 25_120.55 is the same as the number 25120.55.
Example 1: Basic arithmetic operations on numbers in Ruby is shown below. In Ruby, mathematical operations result in an integer only if all numbers used are integer numbers unless we get the result as a float.
# Addition of two integers puts 2 + 3 # Addition of integer and float puts 2 + 3.0 # Subtraction of two integers puts 5 - 3 # Multiplication and division of two integers puts 2 * 3puts 6 / 2 # Exponential operation puts 2 ** 3 |
Output:
5 5.0 2 6 3 8
Example 2: In Ruby, for Modulus(%) operator the sign of the result is always the same as the sign of the second operand. So, 10 % -3 is -2 and -10 % 3 is 2.
# Modulus operatio on numbers puts 10 % 3puts 10 % -3puts -10 % 3 |
Output:
1 -2 2
Example 3: Other mathematical operations on numbers in Ruby is shown below.
num1 = -20num2 = 10.2 # abs() method returns absolute value of number puts num1.abs() # round() method returns the number after rounding puts num2.round() # ceil() and floor() function for numbers in Ruby puts num2.ceil() puts num2.floor() |
Output:
20 10 11 10
Recommended Posts:
- Private Classes in Ruby
- Ruby | Matrix cofactor() function
- Ruby Integer odd? function with example
- Ruby Integer div() function with example
- Ruby | Symbol to_s function
- Ruby | Set replace() function
- Ruby | Set reset() function
- Ruby For Beginners
- Ruby | Array Concatenation using (+) function
- Ruby | at() function
- Ruby Float to_r() method with example
- Ruby | Keywords
- Ruby | Exception Class and its Methods
- Ruby | String inspect Method
- Ruby | Numeric imaginary() function
- Ruby | Numeric i() function
- Ruby | Numeric fdiv() function
- Ruby | String hex Method
- Ruby | String include? Method
- Ruby | Hash each_pair() function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

