Menu
CoddyTech

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.5

Without 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 icon

Challenge

Beginner

Under the comment, create three variables with converted values:

  • int_price: the value of price converted to an int
  • level: the text in level_text converted to an int
  • coins_float: the value of coins converted to a float

Do not change the other lines. The program prints:

Price: 99.99
Int Price: 99
Level: 7
Coins: 15.0

Try 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)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online GDScript compiler