Reference · Math
math.trunc
math.trunc(num) -> intWhat it does
The number with its fraction dropped, as an int: rounding toward zero, as Python's
math.trunc. math.trunc(3.7) is 3 and math.trunc(-3.7) is -3. An int is
itself. It is what int does to a float, but a value that is
not a number is a runtime error here rather than an error value.
Examples
print(math.trunc(3.7), math.trunc(-3.7), math.trunc(7))print(math.trunc(2.9) == int(2.9), type_of(math.trunc(2.9)))3 -3 7true intEdge cases
- For a positive number it is math.floor; for a
negative one it is math.ceil:
math.trunc(-0.5)is0. -7 / 2is-3.5, and truncates to-3.- A float past what an int holds (2^63, about 9.22 × 10¹⁸) is a runtime error,
integer overflow; up to it, an int (math.trunc(9.2e18)). math.trunc(a / b)of two ints divides in ints, so it is exact past 2^53, however the call is written (a pipe, a method, the function kept in a variable). A quotient kept in a variable first is a float.
print(math.trunc(-0.5), math.trunc(-7 / 2))print(math.trunc(0.999), math.trunc(-0.999))print(math.trunc(9.2e18), math.trunc(9223372036854775807 / 10))0 -30 09200000000000000000 922337203685477580print(math.trunc(-1e19))line 1: integer overflowErrors
Infinity and NaN cannot be an int and are a runtime error, not an error value; so is
null or any other value that is not a number. A decimal is refused with a hint to
convert it with float.
print(math.trunc(null))line 1: `math.trunc` expects a number as argument 1, got nullChaining
In a pipeline the number comes first:
print(7.9 | math.trunc)print([1.5, -1.5, 2.5] | map(math.trunc))7[1, -1, 2]See also
math.floor, math.ceil, math.modf, int, round
Thread 0 posts
On math.trunc(): questions, tips, corrections, and code that uses it.
No posts yet. The first one opens the thread.
Edit this page on GitHub · every example's output was made by running it (tools/refcheck.mjs) · questions on Discord or r/quillo