Menu
CoddyTech

Integer Division

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

When both values of a division are integers, / gives an integer: the decimal part is dropped.

print(7 / 2) # 3
print(10 / 3) # 3

The result is not rounded: 7 / 2 is 3, not 4. With a negative number the decimal part is dropped as well, so -7 / 2 is -3.

When at least one value is a float, the result is a float and keeps its decimal part:

print(7.0 / 2) # 3.5
print(7 / 2.0) # 3.5

The same rule applies to variables. To get the exact result from two integer variables, convert one of them with float():

var coins := 7
var players := 2
print(coins / players) # 3
print(float(coins) / players) # 3.5

Integer division is useful for whole items: 7 coins shared by 2 players gives each player 3 coins.

challenge icon

Challenge

Easy

17 coins are shared by 5 players. The variables total_coins and players are declared for you.

Declare two more variables:

  • coins_each: the whole number of coins each player gets, using integer division of total_coins by players
  • exact_share: the exact share as a float, using float() on total_coins before dividing

The print() lines are already there and output:

Each player gets: 3 coins
Exact share: 3.4

Try it yourself

extends Node

func _ready():
	var total_coins := 17
	var players := 5
	# Declare coins_each and exact_share below

	# Don't change the lines below
	print("Each player gets: ", coins_each, " coins")
	print("Exact share: ", exact_share)
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