Skip to content
Jennifer Programming Language

convert - explicit type conversion

Enable with use convert;. Conversion functions plus typeOf for runtime kind introspection. Every function returns the converted value or raises a positioned error (see Errors).

jennifer
use io;
use convert;

def n as int init convert.toInt("42");        # parse string -> 42
def f as float init convert.toFloat(5);       # int -> 5.0
def s as string init convert.toString(3.14);  # any -> "3.14"
def b as bool init convert.toBool(0);         # 0 -> false

io.printf("%s\n", convert.typeOf(5 / 2));      # "float" (`/` is true division)
io.printf("%s\n", convert.typeOf(5 // 2));     # "int"

Behavior summary

CallSource kindsBehavior
convert.toInt(v)int / float / string / boolidentity / truncate (deprecated, see below) / parse (base 10) / true=1, false=0
convert.toInt(s, radix)stringparse s in radix 2 / 8 / 10 / 16 (bare digits; strip any 0x / 0o / 0b prefix first)
convert.toFloat(v)int / float / string / boolconvert / identity / parse decimal (sign, digits, point, exponent; no _, hex, NaN or Inf) / true=1.0, false=0.0
convert.toString(v)anyalways succeeds; uses the value's display form
convert.toBool(v)bool / int / float / stringidentity / canonical only (0/1, 0.0/1.0, "true"/"false")
convert.typeOf(v)anyreturns the kind as a string: "int", "float", ..., "list", "map", "object"
convert.objectType(v)objectspecific registered name of an opaque object, e.g. "json.Value"; errors on a non-object
convert.toCodepoint(char)stringUnicode code point (int) of a one-rune string; errors unless the argument is exactly one code point (a lone invalid UTF-8 byte is an error)
convert.fromCodepoint(n)intthe one-rune string for code point n; errors on a negative / out-of-range / surrogate value

Text and bytes meet in one place, encoding.encode / decode. convert.bytesFromString / stringFromBytes, a UTF-8-only copy of them with the same arguments, and the radix form convert.toString(n, radix) (now io.sprintf("%d|base=16", n)) were removed in 0.28.0; lint L302 points at a leftover call.

toInt of a float

convert.toInt(f) truncates toward zero until 0.29.0; jennifer lint reports (L301) a call whose argument's static type is float, other than an integral literal such as 3.0. From 0.29.0 it accepts only an integral float (3.0 -> 3) and throws "runtime" for any other, so the caller states the rounding with a math function, which returns the int:

WantedCall
toward zero (today's result)math.trunc(f)
nearest, half away from zeromath.round(f)
down / upmath.floor(f) / math.ceil(f)

toCodepoint / fromCodepoint: code point, not "character"

These convert between a single code point (a Unicode scalar value, an int) and the one-rune string that holds it: the primitive a Unicode algorithm needs (Punycode digits, a \x01 control byte, an escape).

  • The whole range works, not just ASCII or the BMP. fromCodepoint accepts any scalar value 0..0x10FFFF (hex literals are fine: fromCodepoint(0x20AC) is €, fromCodepoint(0x1F602) is 😂). The result is one rune whose UTF-8 encoding is 1 to 4 bytes; a code point is not a byte. Only a negative value, one above 0x10FFFF, or a UTF-16 surrogate (0xD800..0xDFFF) errors.
  • "One rune" is not "one character a reader sees." A user-perceived character (a grapheme cluster) can be several code points: a base plus combining marks (e + U+0301 = é), an NFD-decomposed accent, an emoji ZWJ sequence (👨‍👩‍👧). Each of those code points round-trips individually, but toCodepoint takes exactly one code point, so it rejects a multi-rune cluster the same way it rejects "ab". len, strings.chars, and slicing ($s[a..b]) are all rune-indexed too (see strings.md); Jennifer has no grapheme-cluster API. The tell: precomposed é (U+00E9) is len 1 and toCodepoint gives 233; decomposed é (e + U+0301) is len 2 and toCodepoint errors.

Errors and messages

Errors

KindRaised for
"convert"a string that does not parse in toInt (either form), toFloat or toBool: not a number, out of the int range, a 0x / 0o / 0b prefix, NaN, a float that overflows, a bool other than "true" / "false"
"runtime"misuse: a wrong argument count or type, an unsupported radix or a radix on a non-string, a program value with no result (null, a NaN or out-of-range float to toInt, an int other than 0 / 1 or a float other than 0.0 / 1.0 to toBool), toCodepoint / fromCodepoint arguments
jennifer
use io;
use convert;

try {
    convert.toInt("12a");
} catch (e) {
    io.printf("%s\n", $e.kind);   # convert
}

Messages

CallError
convert.toInt("abc")Parse failure: the string is not a valid integer.
convert.toInt(s, radix)An unsupported radix, a digit out of range for the base, a radix on a non-string value, or a 0x / 0o / 0b prefix (strip it first). convert.toInt("41", 16) is 65.
convert.toInt(null)No conversion defined.
convert.toInt(f)A NaN, +/-Infinity, or out-of-int64-range float has no representable integer.
convert.toBool("maybe")Strings: only "true" and "false".
convert.toBool(123), convert.toBool(-1)Ints: only 0 and 1.
convert.toBool(1.5)Floats: only 0.0 and 1.0.
anyToo many or too few arguments.

For "any nonzero counts as true" semantics, write the comparison explicitly:

jennifer
def b as bool init $count != 0;     # not convert.toBool($count)

This matches Jennifer's strict-conditions rule: to project an arbitrary value into a bool, state the criterion.

Notes on the verb naming

The convert library's four conversion callees are named toInt, toFloat, toString, toBool (not int / float / string / bool) so they don't collide with the type keywords, which the parser reserves for declarations (def x as int ...). typeOf is a normal identifier, not a type keyword.

The bare form (int("42"), string(42), ...) is a parse error pointing at the convert.to* form.

Objects: typeOf vs objectType

Some libraries hand back an opaque object: a value that carries data but exposes it only through that library's own accessors, not through operators or [index] / .field, such as json.Value (from json.decode). For any such value convert.typeOf returns the generic "object", and convert.objectType returns the specific registered name so you can tell one object family from another:

jennifer
def doc as json.Value init json.decode("\{\}");
io.printf("%s\n", convert.typeOf($doc));       # object
io.printf("%s\n", convert.objectType($doc));   # json.Value

convert.objectType errors on a non-object, so guard with convert.typeOf(v) == "object" first if the kind is unknown.

See also: encoding.md (all other character and binary-to-text codecs), ../user-guide/index.md, ../technical/interpreter.md, index.md.