Numbers are numerical values and can be integer or floating values.
In Ruby, Numbers data types are used to store numerical values for a variable.
- Ruby integers
Integers are numerical values without decimal values. For example, 1,455 are integers.
Integers contain different type of numerical values such as binary, octal, hex and decimal values
Decimal
are numbers containing 0 to 9 digits. Base is 10 Examples are 11, 19Octal
Numbers are numbers containing 0 to 7, Base is 8. These numbers are declared by the prefix 0. For example, decimal 9 is represented in 011 in octal form.Hexa
decimals are numbers that contain 0-9 and A digits. The base is 16. These numbers are prefixed with 0x. Example numbers are0x1b
.Binary
Numbers are numbers that contain 0 or 1. The base is 2. These numbers are prefixed with0b
.
Here an examples
number = 90
# Prefix 0 for the octal number
number1 = 011 # Outputs 9
# Prefix 0X for Hexa Decimal number
number2 = 0X1b # Outputs 27
# Prefix 0X for Hexa Decimal number
number3 = 0b11 # Outputs 2
- Ruby Floating Numbers
Floating numbers are numbers that contains decimals, It can be in two forms Numbers with decimals
number=1.11
Another way to represent exponentiation numbers in representing the scientific calculation
number=3.4e2 # Outputs 3.4 * 10 power 2
Ruby Number Conversion methods
to_i
: convert a floating number to an integer
number = 11.12.to_i
puts number # 11
to_f
: convert an integer to floating number
number = 12.to_f
puts number # 12.0
- to_r: converts the value as a rational number
number = 3.to_r
puts number # 2/1
Ruby number types
- Rational Number
- Bignum
- BigDecimal
- Complex Number
- Prime Number
- Random Number
- Range of Numbers