Skip to main content

Numbers

Numbers can be written as normal:

  • Integers: For example 16 to denote the integer (base 10) number 16.
  • Floats: For example, 3.14 to denote the decimal number 3.14.
  • In a local declaration such as x = 2.3;, hovering over x shows a tooltip indicating its type is Float, whereas hovering over x in x = 2; shows Number.
    • In the future, the name Number will be deprecated in favour of Integer.

Range of Numeric Values

Numbers (both integer and floating point) range from -9,223,372,036,854,775,807 to 9,223,372,036,854,775,807.

⚠️ The closer to the boundaries, the greater the likelihood for rounding errors; the small floating-point number -9223372036854771.5 rounds to -9223372036854772. Likewise 9223372036854775 results in the approximate number 9223372036854776.

Arithmetic Operators

The following operators work on both integers and floats.

  • -x: Negation
  • x + y: Addition
  • x - y: Subtraction
  • x * y: Multiplication
  • x / y: Division
  • x % y: Modulo
  • x ^ y: Exponentiation
  • sum(list): The sum of a list of integer numbers or a list of floating-point numbers.
    • For example, on integers, sum([1, 2, 3]) equals 6.
    • Likewise, on floats, sum([1.1, 2.1, 3.1]) equals 6.300000000000001.
      • Keep in mind that floating-point arithmetic is generally not precise!
    • You can define a list in various ways, not just as a list of literal numbers. See Lists for more detail on working with lists.
      • Importantly, a list's elements must all be of the same type. As such, sum([1.1, 2, 3.1]) has a type-error since the list is not well-formed. The fix is to replace integer 2 with 2.0 or 2. to have it be treated as a float.

Coercion Operators

To turn a literal integer such as 2 into a float we simply write 2. or 2.0.

  • However, if we have any integer-valued expression, such as x or x + 10, where x is assigned an integer, then we can convert it to a float by writing float(x) or float(x + 10), respectively.
  • Conversely, if we have a float-valued expression E, then we can convert it to an integer by writing int(E).
    • Note that int(E) just truncates any decimal points; e.g., int(2.9) results in 2.

The following table lists the functions that convert an integer to a float:

MethodDescription
int(x)Truncates decimal points
floor(x)Rounds down to the nearest smaller integer
ceil(x)Rounds up to the nearest larger integer
round(x)Rounds to the nearest integer

Note that int(x) and floor(x) have the same behavior.

See also

Types

Functions