Numbers
Int and Float #
Int holds whole numbers of 64 bits. Float holds decimal numbers.
def main() -> Void
puts(7 + 3)
puts(7 - 10)
puts(7 * 3)
puts(1.5 + 2.25)
end10
-3
21
3.75Exponents #
A Float can end in an exponent, e or E with an optional sign: 1.5e-3 is 0.0015 and 2.0E+10 is 20000000000.0. A digit must come before the e, so 1.e5 is not a number, and 1e5 is a Float.
def main() -> Void
puts(1.5e-3)
puts(2.0E+10)
puts(1e5)
end0.0015
20000000000.0
100000.0Long numbers #
A _ between digits is only visual: 1_000 is the same Int as 1000.
def main() -> Void
budget = 1_000_000
rate = 0.000_5
puts(budget)
puts(rate)
puts(1_000 == 1000)
end1000000
0.0005
true1_, 1__0, 1_.5 and 1._5 are LEX-INVALID-NUMBER. s.to_i and s.to_f reject a _ in text.
Hex, binary and octal #
0x, 0b and 0o write an Int in base 16, 2 or 8, as in Ruby. The prefix and the hex letters take either case, and _ separates digits here too.
def main() -> Void
puts(0xFF)
puts(0b1010_1010)
puts(0o755)
puts(0x7FFF_FFFF_FFFF_FFFF)
end255
170
493
9223372036854775807The range is the one of Int: 0x8000_0000_0000_0000 is CHECK-INT-RANGE. A prefix with no digit (0x), a digit outside the base (0b102, 0o8) or a misplaced _ (0xFF_) is LEX-INVALID-NUMBER. A leading zero alone is still decimal: 0755 is 755.
Division #
/ on two Int values cuts off the decimals, toward zero. % is the remainder and works on Int only.
def main() -> Void
puts(7 / 2)
puts(-7 / 2)
puts(7 % 2)
puts(7.0 / 2.0)
end3
-3
1
3.5Dividing by zero stops the program with an error, also for Float:
def main() -> Void
zero = 0
puts(10 / zero)
enderror[RUNTIME-DIVISION-BY-ZERO]Mixing Int and Float #
The two sides of an operator must have the same type. Convert with to_f or to_i!.
def main() -> Void
count = 3
price = 2.5
puts(count.to_f * price)
puts(7.9.to_i!)
end7.5
7Comparison #
<, <=, > and >= compare two numbers of the same type. == and != work on numbers, Bool, String and nil.
def main() -> Void
puts(3 < 5)
puts(2.5 >= 2.5)
puts(4 == 4)
puts(4 != 5)
endtrue
true
true
trueComparisons do not chain. Write a < b and b < c.
Negative numbers #
A minus sign is an operator. Use parentheses to call a method on a negative literal:
def main() -> Void
puts((-5).to_s + " degrees")
end-5 degreesText to numbers #
to_i and to_f read a number from a string. They give a Result, because the text may not be a number. to_i! and to_f! give the number and stop the program on bad text.
def main() -> Void
puts("42".to_i)
puts("4x".to_i)
puts("42".to_i! + 1)
puts("2.5".to_f!)
endok(42)
error("cannot convert \"4x\" to Int", kind: "number.parse")
43
2.5Overflow #
Int overflow is an error. It never wraps around.
def main() -> Void
big = 9223372036854775807
puts(big + 1)
enderror[RUNTIME-INTEGER-OVERFLOW]See Int and Float for all conversion functions.