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 + 5adds 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
EasyWrite a program that reads two numbers and prints their product.
- Read the first number from the input and cast it to
float. - Read the second number the same way.
- 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.0A 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
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