Skip to content

Commit 2ec0b55

Browse files
[Edit]: Lua math.floor (#6973)
* [Edit] SQL: DATEDIFF() * Update datediff.md * [Edit]: Lua `math.floor()` * fixed format * Update content/lua/concepts/mathematical-library/terms/floor/floor.md * Update content/lua/concepts/mathematical-library/terms/floor/floor.md * Update content/lua/concepts/mathematical-library/terms/floor/floor.md ---------
1 parent 2774cf6 commit 2ec0b55

File tree

1 file changed

+206
-24
lines changed
  • content/lua/concepts/mathematical-library/terms/floor

1 file changed

+206
-24
lines changed
Lines changed: 206 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
---
2-
Title: 'floor()'
3-
Description: 'Used to round down a value to the closest integer less than or equal to that value.'
2+
Title: 'math.floor()'
3+
Description: 'Rounds a number down to the nearest integer.'
44
Subjects:
55
- 'Computer Science'
6-
- 'Game Development'
6+
- 'Web Development'
77
Tags:
8-
- 'Arithmetic'
98
- 'Functions'
109
- 'Math'
1110
- 'Numbers'
@@ -14,56 +13,239 @@ CatalogContent:
1413
- 'paths/computer-science'
1514
---
1615

17-
In Lua, the **`math.floor()`** function is a standard function that is part of the Lua `math` library. The `math.floor()` function is used to round down a given value to its closest integer value that is less than or equal to the given value.
16+
The **`math.floor()`** function is a built-in mathematical function in Lua that rounds a number down to the nearest integer. It returns the largest integer less than or equal to the given number, effectively rounding down any fractional value.
1817

19-
> **Note:** `math.floor()` always returns a value equal to or less than the given value. It _does not_ round up under any circumstances. For example, `math.floor(2.999)` returns 2 as that is the closest integer value that is _less than or equal_ to 2.999. To round numbers in either direction, use `math.round()`.
18+
The `math.floor()` function is commonly used in programming scenarios where precise integer values are needed, such as array indexing, pagination calculations, converting measurements to whole units, creating stepped progress bars, and implementing floor division algorithms. It's beneficial in game development for coordinate calculations, financial applications for currency rounding, and data processing where fractional values need to be eliminated while maintaining mathematical accuracy.
2019

2120
## Syntax
2221

23-
As `floor()` is a method that is a part of the standard Lua `math` library, it must be called as `math.floor()`.
24-
2522
```pseudo
26-
math.floor(mycoolvalue) -- Returns the closest integer value that is less than or equal to mycoolvalue
23+
math.floor(x)
24+
```
25+
26+
**Parameters:**
27+
28+
- `x`: A numeric value (integer or float) that will be rounded down to the nearest integer.
29+
30+
**Return value:**
31+
32+
The `math.floor()` function returns an integer value representing the largest integer less than or equal to the input parameter `x`. The function returns the same integer value if the input is already an integer.
33+
34+
## Example 1: Basic Floor Operation
35+
36+
This example demonstrates the fundamental usage of `math.floor()` with positive decimal numbers:
37+
38+
```lua
39+
-- Basic floor operation with positive numbers
40+
local value1 = 7.8
41+
local value2 = 12.1
42+
local value3 = 5.999
43+
44+
-- Apply floor function to each value
45+
local result1 = math.floor(value1)
46+
local result2 = math.floor(value2)
47+
local result3 = math.floor(value3)
48+
49+
-- Display the results
50+
print("math.floor(" .. value1 .. ") = " .. result1)
51+
print("math.floor(" .. value2 .. ") = " .. result2)
52+
print("math.floor(" .. value3 .. ") = " .. result3)
53+
```
54+
55+
The output for this code is:
56+
57+
```shell
58+
math.floor(7.8) = 7
59+
math.floor(12.1) = 12
60+
math.floor(5.999) = 5
2761
```
2862

29-
## Example 1
63+
This example shows how `math.floor()` consistently rounds down to the nearest integer regardless of how close the decimal portion is to the following whole number. Even 5.999 rounds down to 5, not up to 6.
64+
65+
## Example 2: Array Indexing with Floor
3066

31-
To find the closest integer less than or equal to 1.234:
67+
This example demonstrates a practical use case where `math.floor()` ensures proper array indexing by converting floating-point calculations to valid integer indices:
3268

3369
```lua
34-
print(math.floor(1.234))
70+
-- Simulating array indexing with calculated positions
71+
local inventory = {"sword", "shield", "potion", "key", "scroll"}
72+
local totalItems = #inventory
73+
74+
-- Calculate position based on percentage (results in decimal)
75+
local percentage = 0.75 -- 75% through the array
76+
local calculatedIndex = percentage * totalItems
77+
78+
-- Use math.floor to get valid array index
79+
local actualIndex = math.floor(calculatedIndex)
80+
81+
-- Ensure we have a valid index (Lua arrays start at 1)
82+
if actualIndex == 0 then
83+
actualIndex = 1
84+
end
85+
86+
print("Calculated index: " .. calculatedIndex)
87+
print("Floored index: " .. actualIndex)
88+
print("Item at index " .. actualIndex .. ": " .. inventory[actualIndex])
89+
90+
-- Another example with different percentage
91+
local lowPercentage = 0.2 -- 20% through the array
92+
local lowIndex = math.floor(lowPercentage * totalItems)
93+
if lowIndex == 0 then lowIndex = 1 end
94+
95+
print("20% through array gives index: " .. lowIndex)
96+
print("Item: " .. inventory[lowIndex])
3597
```
3698

37-
This results in the following output:
99+
The output of this code will be:
38100

39101
```shell
40-
1
102+
Calculated index: 3.75
103+
Floored index: 3
104+
Item at index 3: potion
105+
20% through array gives index: 1
106+
Item: sword
41107
```
42108

43-
## Example 2
109+
This example shows how `math.floor()` prevents array indexing errors by ensuring calculated indices are always valid integers, which is essential when working with dynamic positioning in arrays.
110+
111+
## Example 3: Financial Calculations
44112

45-
It is important to remember that `math.floor()` does not perform rounding, as in the following example:
113+
This example demonstrates using `math.floor()` in financial calculations where monetary values need to be rounded down to avoid overcharging customers:
46114

47115
```lua
48-
print(math.floor(2.999))
116+
-- Financial calculation example - discount pricing
117+
local originalPrices = {29.99, 45.67, 12.34, 78.90}
118+
local discountRate = 0.15 -- 15% discount
119+
120+
print("Original Price -> Discounted Price (floored)")
121+
print("==========================================")
122+
123+
for i = 1, #originalPrices do
124+
local originalPrice = originalPrices[i]
125+
126+
-- Calculate discount amount
127+
local discountAmount = originalPrice * discountRate
128+
129+
-- Calculate discounted price
130+
local discountedPrice = originalPrice - discountAmount
131+
132+
-- Use math.floor to round down to nearest cent
133+
-- Multiply by 100, floor, then divide by 100 for cents precision
134+
local flooredPrice = math.floor(discountedPrice * 100) / 100
135+
136+
print(string.format("$%.2f -> $%.2f", originalPrice, flooredPrice))
137+
end
138+
139+
-- Calculate total savings
140+
local totalOriginal = 0
141+
local totalDiscounted = 0
142+
143+
for i = 1, #originalPrices do
144+
totalOriginal = totalOriginal + originalPrices[i]
145+
146+
local discountedPrice = originalPrices[i] * (1 - discountRate)
147+
local flooredPrice = math.floor(discountedPrice * 100) / 100
148+
totalDiscounted = totalDiscounted + flooredPrice
149+
end
150+
151+
local totalSavings = totalOriginal - totalDiscounted
152+
print("==========================================")
153+
print(string.format("Total Original: $%.2f", totalOriginal))
154+
print(string.format("Total After Floor Discount: $%.2f", totalDiscounted))
155+
print(string.format("Total Savings: $%.2f", totalSavings))
49156
```
50157

51-
This will yield the following output:
158+
The output of this code will be:
52159

53160
```shell
54-
2
161+
Original Price -> Discounted Price (floored)
162+
==========================================
163+
$29.99 -> $25.49
164+
$45.67 -> $38.81
165+
$12.34 -> $10.48
166+
$78.90 -> $67.06
167+
==========================================
168+
Total Original: $166.90
169+
Total After Floor Discount: $141.84
170+
Total Savings: $25.06
55171
```
56172

57-
## Example 3
173+
This example illustrates how `math.floor()` is used in financial applications to ensure customers are never overcharged due to rounding, while businesses can maintain predictable pricing structures.
174+
175+
## Example 4: Use Cases for Negative Numbers
58176

59-
When working with negative numbers, it is important to remember that `math.floor()` returns the closest integer _less than or equal_ to a given value:
177+
This example shows how `math.floor()` behaves with negative numbers, which is crucial for understanding its mathematical definition:
60178

61179
```lua
62-
print(math.floor(-4.56))
180+
-- Working with negative numbers
181+
local negativeValues = {-2.3, -5.7, -10.1, -0.5}
182+
183+
print("Understanding math.floor() with negative numbers:")
184+
print("================================================")
185+
186+
for i = 1, #negativeValues do
187+
local value = negativeValues[i]
188+
local flooredValue = math.floor(value)
189+
190+
print(string.format("math.floor(%.1f) = %d", value, flooredValue))
191+
end
192+
193+
-- Comparison with positive equivalents
194+
print("\nComparison with positive numbers:")
195+
print("=================================")
196+
197+
local testValues = {2.3, -2.3, 5.7, -5.7}
198+
199+
for i = 1, #testValues do
200+
local value = testValues[i]
201+
local flooredValue = math.floor(value)
202+
203+
if value > 0 then
204+
print(string.format("Positive: math.floor(%.1f) = %d", value, flooredValue))
205+
else
206+
print(string.format("Negative: math.floor(%.1f) = %d", value, flooredValue))
207+
end
208+
end
63209
```
64210

65-
This results in the following output:
211+
The output of this code will be:
66212

67213
```shell
68-
-5
214+
Understanding math.floor() with negative numbers:
215+
================================================
216+
math.floor(-2.3) = -3
217+
math.floor(-5.7) = -6
218+
math.floor(-10.1) = -11
219+
math.floor(-0.5) = -1
220+
221+
Comparison with positive numbers:
222+
=================================
223+
Positive: math.floor(2.3) = 2
224+
Negative: math.floor(-2.3) = -3
225+
Positive: math.floor(5.7) = 5
226+
Negative: math.floor(-5.7) = -6
69227
```
228+
229+
> **Note:** With negative numbers, `math.floor()` rounds toward negative infinity, not toward zero. This means -2.3 becomes -3, not -2.
230+
231+
## Frequently Asked Questions
232+
233+
### 1. What's the difference between `math.floor()` and `math.ceil()`?
234+
235+
`math.floor()` always rounds down toward negative infinity, while `math.ceil()` always rounds up toward positive infinity. For positive numbers, floor rounds are placed toward zero, and ceil rounds are placed away from zero.
236+
237+
### 2. Does `math.floor()` work with negative numbers?
238+
239+
Yes, but it's important to understand that `math.floor()` rounds toward negative infinity. This means -2.3 becomes -3, not -2, because -3 is the largest integer less than or equal to -2.3.
240+
241+
### 3. What happens if I pass an integer to `math.floor()`?
242+
243+
If you pass an integer to `math.floor()`, it returns the same integer unchanged. For example, `math.floor(5)` returns 5.
244+
245+
### 4. What happens if I pass a string to `math.floor()`?
246+
247+
Passing a string to `math.floor()` will result in an error. The function expects a numeric value. Use `tonumber()` to convert strings to numbers first if needed.
248+
249+
### 5. Is there a performance difference between `math.floor()` and other rounding methods?
250+
251+
`math.floor()` is highly optimized and generally very fast. It's typically more efficient than manual rounding approaches and is the standard way to perform floor operations in Lua.

0 commit comments

Comments
 (0)