int
func int[T: Number](x: T): intint converts x to int, which is int64, exactly. It panics if x is out of range, has a fraction, or is NaN or infinite; int(Math.trunc(x)) truncates. x may also be a named primitive over a number.
Details
- To convert a float with a fraction, round it first with Math.trunc, Math.round, or Math.floor. To get
nullinstead of a panic, use Math.toInt. intconverts numbers only. To read anintfrom text, use String.toInt.
Basic examples
Convert a smaller integer kind to int:
int(byte(200)) // 200
int(int8(-5)) // -5Convert a float with no fraction:
int(3.0) // 3
int(-0.0) // 0Truncate a float toward zero first, then convert:
int(Math.trunc(2.7)) // 2
int(Math.trunc(-2.7)) // -2Scope
Every numeric kind converts, as long as the value fits:
int(uint64(9223372036854775807)) // 9223372036854775807
int(float32(2.5) * float32(2.0)) // 5
int(1e18) // 1000000000000000000
int(7) // 7A named primitive over a number is unwrapped:
type Count = int
type Celsius = float64
int(Count(4)) + 1 // 5
int(Celsius(21.0)) // 21Pass int itself as a function:
[1.0, 2.0, 3.0].map(int) // [1, 2, 3]Applications
Add bytes without overflowing byte by summing them as int:
let data = [byte(200), byte(100), byte(50)]
data.map(int).sum() // 350Turn a price in dollars into whole cents, rounding first:
func cents(price: float64): int {
int(Math.round(price * 100.0))
}
cents(19.99) // 1999
cents(0.1) // 10Split a duration in seconds into minutes and seconds:
let elapsed = 754.6
let total = int(Math.floor(elapsed))
"${total / 60}m ${total % 60}s" // "12m 34s"Properties and relations
An int survives a round trip through float64 when float64 represents it exactly:
for n in [0, 1, -42, 4503599627370496] {
assert(int(float64(n)) == n)
}int(x) agrees with Math.toInt wherever it does not panic:
for x in [3.0, -8.0, 1e15] {
assert(Math.toInt(x) == int(x))
}
Math.toInt(2.5) // nullPossible issues
A float with a fraction panics instead of rounding:
int(2.5) // panic: 2.5 has a fraction, so it does not convert to intFloat arithmetic often leaves a fraction you do not see in the source:
int(0.1 + 0.2) // panic: 0.30000000000000004 has a fraction, so it does not convert to intValues out of range panic, and so do NaN and the infinities:
int(Math.maxUint64) // panic: 18446744073709551615 out of range for int
int(9.3e18) // panic: 9300000000000000000.0 out of range for int
int(Math.NaN) // panic: NaN does not convert to int
int(Math.Infinity) // panic: Infinity does not convert to intint does not parse text; that is a compile error:
let n = int("3") // error: int converts a number or a named primitive type over a number, got stringA nullable number must be narrowed first:
let found: int | null = [5, 6].indexOf(6)
let n = int(found)
// error: int converts a number or a named primitive type over a number, got int | nullSee also
int64, float64, byte, Math.toInt, Math.trunc, Math.round, String.toInt, String.from
