Menu
CoddyTech

Cast

Part of the Fundamentals section of Coddy's GDScript journey. Lesson 35 of 92.

Input is always a String. To do math with it, cast it to a number with int() or float(), the functions from the Type Casting lesson:

var text := OS.read_string_from_stdin()
var age := int(text)

Or in one line:

var age := int(OS.read_string_from_stdin())

The type decides what + does:

  • "5" + "5" joins two strings: "55"
  • 5 + 5 adds two numbers: 10

Use int() for whole numbers and float() for numbers with a decimal point. With the input 4.5, float() gives 4.5, but int() stops at the decimal point and gives 4.

A cast does not stop the program when the text is not a number. int("hello") is 0, and int("5ab") is 5, so a typo in the input turns into a wrong number instead of an error.

To turn a number back into text, use str(): str(42) is "42".

challenge icon

Challenge

Easy

Write a program that reads two numbers and prints their product.

  1. Read the first number from the input and cast it to float.
  2. Read the second number the same way.
  3. Print the two numbers multiplied together.

Each test gives two lines of input, one number per line. For example, if the inputs are 2 and 4.5, the program prints:

9.0

A float always prints with a decimal point, so 14 times 5 prints 70.0.

Try it yourself

extends Node

func _ready():
	# Read two numbers as floats and print their product
	pass
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