Threadon / Casts

Casts

converting values between types

The cast syntax

To convert a value to a type, call the type like a function with the value inside. It's the only conversion mechanism in the language.

Int32(x)     # to an integer
Int8(x)
Int16(x)
Float32(x)   # to a float
Float16(x)
Bool(x)      # to true or false

The value you convert must be a number, a bool, or a string. Casting a struct is a compile error.

Here's every working cast, all in one program:

def main() -> Int32
    print(Int32(3.7))      # float to int
    print(Int32(True))     # bool to int
    print(Float32(5))    # int to float
    print(Bool(7))        # number to bool
    print(Int32("123"))   # string to int
    print(Float32("3.5")) # string to float
    print(Bool("true"))  # string to bool
    print(Bool("0"))     # string to bool
    return 0
3 1 5.000000 True 123 3.500000 True False

Float to integer

Converting a float to an integer drops the decimal part. It truncates toward zero, not to the nearest whole number.

print(Int32(3.7))    # 3
print(Int32(3.2))    # 3
print(Int32(-3.7))   # -3, not -4

Watch out for an integer overflow. Converting a float that doesn't fit in the target integer gives an error with --debug enabled.

Converting to Bool

Numbers: zero becomes false, anything else becomes true.

print(Bool(0))    # False
print(Bool(7))    # True

Strings: "0", "false", and the empty string are False. Everything else is True. The check ignores capital letters, so "False" is false too.

def main() -> Int32
    print(Bool("true"))
    print(Bool("False"))
    print(Bool("0"))
    print(Bool(""))
    return 0
True False False False

Strings to numbers

A string that holds a number converts to that number. Leading minus signs work. The string is read with strtol for integers and strtod for floats.

print(Int32("123"))    # 123
print(Float32("3.5"))  # 3.5

What happens when the string is not a number at all, like "abc"? That depends on debug mode:

The conversion reads as much of the string as it can. A string like "12abc" becomes 12, since the leading digits parse fine.

Casts make a new value

A cast creates a converted copy. It does not change the original variable.

x: Int32 = 7
print(Float32(x))   # 7.000000
print(x)              # still 7