Mojo Type Conversion
Mojo never changes a value’s type behind your back. If you have an Int and need a Float64, or have the text "42" and need the number 42, you convert it yourself. The good news: almost every conversion looks the same. You write the type you want and pass the value to it, like Float64(x) or String(x). This page shows the common ones and the traps in each.
Why Mojo makes you convert
Section titled “Why Mojo makes you convert”In Python, 3 * 0.5 just works: Python turns the int into a float for you. Mojo won’t do that between variables:
def main(): var count = 3 var price: Float64 = count print(price)hello.mojo:3:26: error: cannot implicitly convert 'Int' value to 'Float64' var price: Float64 = count ^~~~~mojo: error: failed to parse the provided Mojo source module“Implicitly” means “without being asked”. Automatic conversions can hide lost decimals, lost digits or a negative number turning into a huge positive one. So Mojo asks you to write the conversion down, and then anyone reading the code can see it. The numeric types reference has a short section on why conversions are explicit.
Int to Float64
Section titled “Int to Float64”Wrap the value in Float64(...):
def main(): var count = 3 var price = 2.5 var total = Float64(count) * price print(total)Output:
7.5Float64(count) gives a new Float64 value (3.0); count itself stays an Int. Going from Int to Float64 is safe for any number you’re likely to meet. (A Float64 holds about 15 to 16 exact digits, so giant integers beyond that would be rounded.)
Float64 to Int: the fraction is cut off
Section titled “Float64 to Int: the fraction is cut off”Int(...) turns a float into a whole number by dropping everything after the decimal point. It doesn’t round:
def main(): var a = 3.9 var b = -3.9 print(Int(a), Int(b)) print(Int(round(a)), Int(round(b)))Output:
3 -34 -4Int(3.9) is 3, and Int(-3.9) is -3: the fraction is cut toward zero. If you want the nearest whole number, call round first and then convert.
There’s one odd case. Writing a decimal literal straight into Int(...) doesn’t compile at all:
def main(): print(Int(3.9))hello.mojo:1:5: error: function instantiation faileddef main(): ^hello.mojo:2:14: note: call expansion failed print(Int(3.9)) ^Mojo/stdlib/std/simd.mojo:983:9: note: constraint failed: the SIMD type must be floating pointmojo: error: failed to run the pass managerThe message isn’t very clear. The official types and literals cheat sheet puts the rule simply: float literals can’t become integers. In real code the value is almost always in a variable anyway, and then Int(x) works.
Between sized number types
Section titled “Between sized number types”The same pattern works for every number type: Int8(x), UInt16(x), Int64(x), Float32(x) and so on.
def main(): var small: Int8 = 100 var big: Int64 = 5_000_000_000 print(Int(small) + 1) print(Int(big)) print(Float32(big))Output:
10150000000005000000000.0Widening (to a type with more room) is always safe. Narrowing is where you need care. If the value doesn’t fit, Mojo doesn’t stop you. It keeps only the low bits, so the number wraps around:
def main(): var score = 300 var negative = -1 print(Int8(score), UInt8(score)) print(UInt8(negative)) var big: Int64 = 5_000_000_000 print(Int32(big))Output:
44 44255705032704300 doesn’t fit in 8 bits, so you get 44. -1 as a UInt8 becomes 255. No error, no warning. When a value might not fit, check it against the type’s .MIN and .MAX first. The Mojo Integer Overflow lesson shows how.
Numbers to strings
Section titled “Numbers to strings”String(...) turns a number (or a Bool) into text:
def main(): var age = 36 var height = 1.75 var label = "Age: " + String(age) print(label) print(String(height) + " m") print(String(True)) print(String("Items: ", 5, ", total: ", 12.5))Output:
Age: 361.75 mTrueItems: 5, total: 12.5String(...) also takes several values and joins them, like the last line. You only need any of this when you build a string to keep. For printing, print("Age:", age) and t-strings (print(t"Age: {age}")) do the conversion for you.
Strings to numbers
Section titled “Strings to numbers”Going the other way, Int("42") and Float64("3.25") read a number from text. But text might not be a number at all ("hello"), so these conversions can raise an error. Mojo makes you deal with that. If you just call Int("42") in a normal main, it won’t compile:
def main(): var n = Int("42") print(n)hello.mojo:2:16: error: cannot call function that may raise in a context that cannot raise var n = Int("42") ~~~^~~~~~hello.mojo:2:16: note: try surrounding the call in a 'try' block var n = Int("42") ^hello.mojo:1:5: note: or mark surrounding function as 'raises'def main(): ^mojo: error: failed to parse the provided Mojo source moduleThe notes give you two fixes. The quick one is to mark main with raises. Then if the text isn’t a number, the program stops with an error message:
def main() raises: var n = Int("42") var price = Float64("3.25") print(n + 1, price * 2)Output:
43 6.5The better fix, when the text comes from a user or a file, is try and except. They let you catch the problem and carry on:
def main(): var inputs: List[String] = ["42", " 7 ", "3.5", "abc"] for text in inputs: try: print("number:", Int(text)) except e: print("not a whole number:", e)Output:
number: 42number: 7not a whole number: String is not convertible to integer with base 10: '3.5'not a whole number: String is not convertible to integer with base 10: 'abc'A few things to notice:
- Spaces around the number are fine:
" 7 "becomes7. Int("3.5")fails: a decimal isn’t a whole number. UseFloat64("3.5")for that.Float64(...)also understands forms like"2.5e3".
You’ll learn the full story of raises, try and except in Mojo Errors and Mojo Try/Except. The for loop gets its own lesson too; here it just runs the try once per item.
Booleans
Section titled “Booleans”Bool(...) turns a value into True or False (zero and empty values are False), and Int(...) turns a Bool into 1 or 0:
def main(): print(Bool(0), Bool(5), Bool(""), Bool("no")) print(Int(True), Int(False))Output:
False True False True1 0Careful: Bool("no") is True, because the string isn’t empty. Converting text like "yes" or "false" into a Bool means comparing it yourself, for example answer == "yes".
Cheat sheet
Section titled “Cheat sheet”| From | To | Write | Watch out for |
|---|---|---|---|
Int |
Float64 |
Float64(n) |
Nothing, for normal numbers |
Float64 |
Int |
Int(x) |
Cuts the fraction: 3.9 becomes 3. Use round first. |
Int |
Int8, UInt8, … |
Int8(n) |
Wraps silently if it doesn’t fit |
Int8, Int64, … |
Int |
Int(n) |
Nothing, for the usual 64-bit Int |
number or Bool |
String |
String(n) |
Nothing |
String |
Int |
Int(s) |
Can raise: needs try or raises |
String |
Float64 |
Float64(s) |
Can raise: needs try or raises |
| anything | Bool |
Bool(x) |
Any non-empty string is True |
Practice
Section titled “Practice”1. Average as a decimal
Section titled “1. Average as a decimal”Given var total = 17 and var count = 4, print the average as a decimal number.
Hint: convert before you divide.
Show solution
def main(): var total = 17 var count = 4 var average = Float64(total) / Float64(count) print(average)Output:
4.25With two Int values, / would give 4. Converting to Float64 first keeps the .25.
2. Read numbers from text
Section titled “2. Read numbers from text”Two prices arrive as text: "19.99" and "5.01". Convert them, add them, and print Total: 25.0.
Hint: Float64(...) can raise, so mark main with raises.
Show solution
def main() raises: var a = Float64("19.99") var b = Float64("5.01") print("Total: " + String(a + b))Output:
Total: 25.0Each Float64(...) reads a number from the text. String(...) turns the sum back into text so it can be joined with +.
3. Safe age input
Section titled “3. Safe age input”Write a program that converts "thirty" with Int(...) inside a try block. If it works, print the age; if not, print Please type a number.
Hint: put the conversion and the print in try:, and the fallback in except:.
Show solution
def main(): var text = "thirty" try: var age = Int(text) print("Age:", age) except: print("Please type a number.")Output:
Please type a number.Int("thirty") raises, so Mojo jumps straight to the except block. Change text to "30" and it prints Age: 30 instead.
- Mojo never converts types for you. Write the type you want:
Float64(x),Int(x),String(x). Int(x)on a float cuts the fraction toward zero. Useroundfirst for the nearest whole number.- Narrowing to a smaller type (
Int8(300)) wraps silently. Check the range first. String(x)turns numbers and booleans into text, and can join several values.Int(s)andFloat64(s)can raise, so usetry/exceptor mark the functionraises.Bool(x)follows truthiness: any non-empty string isTrue.
Next up: constants, values fixed at compile time with comptime.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Numeric types reference: the “Explicit conversions” and “Sharp edges” sections cover number conversions in detail.
- Mojo manual: Types: the “Numeric type conversion” section, plus how
String(...)works withWritable. - Types and literals cheat sheet: conversion rules and the literal edge cases on one page.
SIMDAPI docs: the__init__andcastsections show exactly how values wrap and truncate.atolAPI docs: the function behind string-to-integer parsing, including other number bases.