Type Casting
Part of the Fundamentals section of Coddy's GDScript journey. Lesson 14 of 92.
Type casting converts a value from one type to another. In GDScript you write the name of the new type and put the value in parentheses: int(), float() or str().
var whole := int(3.9) # 3
var decimal := float(5) # 5.0
var text := str(42) # "42"int() removes the decimal part without rounding: int(3.9) is 3, and int(-3.9) is -3.
Casting also turns text into numbers. "7" is a String, so it cannot go into an int variable until you convert it:
var level_text := "7"
var level: int = int(level_text) # 7
var price := float("2.5") # 2.5Without int(), var level: int = level_text is an error, because level_text holds a String.
str() turns any value into text: str(2.5) is "2.5" and str(true) is "true".
Text that is not a number does not stop the program. int("abc") gives 0, so an unexpected 0 often means the text was not a number.
Challenge
BeginnerUnder the comment, create three variables with converted values:
int_price: the value ofpriceconverted to anintlevel: the text inlevel_textconverted to anintcoins_float: the value ofcoinsconverted to afloat
Do not change the other lines. The program prints:
Price: 99.99
Int Price: 99
Level: 7
Coins: 15.0Try it yourself
extends Node
func _ready():
var price := 99.99
var level_text := "7"
var coins := 15
# Convert the values below
# Don't change the lines below
print("Price: ", price)
print("Int Price: ", int_price)
print("Level: ", level)
print("Coins: ", coins_float)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsInteger DivisionModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators10Functions
Declare a FunctionArgumentsReturnReturn TypesRecap - Sigma FunctionRecap - Validation FunctionDefault Values5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Ternary OperatorPractice on your own: Online GDScript compiler