Skip to content

Type conversions#

CEL provides functions to convert values between types.

Numeric conversions#

Convert between numeric types using int(), uint(), and double().

int(3.9)
// result: 3 (int)
int(-3.9)
// result: -3 (int)
uint(42)
// result: 42 (uint)
double(42)
// result: 42 (double)

Converting a negative value to uint produces an error.

uint(-1)
// error: unsigned integer overflow

String conversions#

Convert values to strings using string().

string(42)
// result: "42" (string)
string(3.14)
// result: "3.14" (string)
string(true)
// result: "true" (string)

Parse strings to numbers using int(), uint(), or double(). Strings must contain decimal digits only (no hex or type suffixes).

int("42")
// result: 42 (int)
int("-42")
// result: -42 (int)
double("3.14")
// result: 3.14 (double)
double("3.14e10")
// result: 3.14e+10 (double)

Special floating-point values can be parsed from strings.

double("NaN")
// result: NaN (double)
double("Infinity")
// result: +Inf (double)

Invalid strings produce an error.

int("0x2A")
// error: type conversion error from 'string' to 'int'

Bytes conversions#

Convert between strings and bytes.

bytes("hello")
// result: b"hello" (bytes)
string(b"hello")
// result: "hello" (string)

Converting bytes to string requires valid UTF-8.

string(b"\xff\xfe")
// error: invalid UTF-8 in bytes, cannot convert to string

Time conversions#

Convert timestamps to Unix epoch seconds.

int(timestamp("2023-01-01T00:00:00Z"))
// result: 1672531200 (int)

Convert durations to nanoseconds.

int(duration("1h"))
// result: 3600000000000 (int)

Dynamic type#

dyn() marks a value as dynamically typed, deferring type checking to runtime.

dyn(42)
// result: 42 (int)

This is useful when the ternary operator branches have different types.

true ? dyn(1) : dyn("one")
// result: 1 (int)

See also#