Rounding

Lua has a collection of ready-made math functions called math. You call them like print: write the name and then the values in parentheses. Unlike print, they don't print anything. They calculate a result and return it: they give it back to the program, which can print it or store it in a variable.

Two of them round numbers:

  • math.floor(x) rounds down, toward the floor: math.floor(3.7) is 3.
  • math.ceil(x) rounds up, toward the ceiling (ceil is short for ceiling): math.ceil(3.2) is 4.

Both return an integer. That's also how you get rid of the .0 after a division:

local weight = 7.6    -- a pumpkin, in kilograms
print(math.floor(weight))
print(math.ceil(weight))
print(10 / 2)
print(math.floor(10 / 2))

This prints:

7
8
5.0
5

Down means toward smaller numbers, also below zero: math.floor(-3.5) is -4.

Lua has no function that rounds to the nearest whole number. math.round(7.6) ends with the error attempt to call a nil value (field 'round'): there's nothing called round in math, so there's nothing to call. To round to the nearest whole number, add 0.5 and round down:

print(math.floor(7.6 + 0.5))
print(math.floor(7.4 + 0.5))

This prints:

8
7

Three more useful functions:

  • math.max(a, b, …) returns the largest of the values you give it, and math.min(a, b, …) the smallest. You can give them as many values as you like.
  • math.abs(x) returns the absolute value: the number without its minus sign. math.abs(-3) is 3.
local morning = -3    -- degrees
local noon = 5
print(math.max(morning, noon, 2))
print(math.min(morning, noon, 2))
print(math.abs(morning - noon))

This prints:

5
-3
8

The temperature rose by 8 degrees. morning - noon is -8, and math.abs makes the difference positive, whichever number comes first.

math.min and math.max are also handy for limits. For example, Emma has 7 plots, so even with 10 packets of seeds, she can plant at most math.min(packets, 7) of them.

Instructions

Run the program. Emma can't walk to the well 5.625 times: she has to go there 6 times, and on the last trip her can is only partly full. Round the number of trips up with math.ceil, so that the program prints:

Trips to the well: 6

At the end of the program, print the most eggs the hens laid in one day. Use math.max with the three variables:

Trips to the well: 6
Most eggs in a day: 9

On the next line, print the average number of eggs a day, rounded down: add up the three days, divide the sum by 3, and round it down with math.floor. (Without rounding, it would be 6.6666666666667.)

Trips to the well: 6
Most eggs in a day: 9
Average: 6 eggs a day

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

4/10