Lua math.floor()
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.
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.
Syntax
math.floor(x)
Parameters:
x: A numeric value (integer or float) that will be rounded down to the nearest integer.
Return value:
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.
Example 1: Basic Floor Operation
This example demonstrates the fundamental usage of math.floor() with positive decimal numbers:
-- Basic floor operation with positive numberslocal value1 = 7.8local value2 = 12.1local value3 = 5.999-- Apply floor function to each valuelocal result1 = math.floor(value1)local result2 = math.floor(value2)local result3 = math.floor(value3)-- Display the resultsprint("math.floor(" .. value1 .. ") = " .. result1)print("math.floor(" .. value2 .. ") = " .. result2)print("math.floor(" .. value3 .. ") = " .. result3)
The output for this code is:
math.floor(7.8) = 7math.floor(12.1) = 12math.floor(5.999) = 5
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.
Example 2: Array Indexing with Floor
This example demonstrates a practical use case where math.floor() ensures proper array indexing by converting floating-point calculations to valid integer indices:
-- Simulating array indexing with calculated positionslocal inventory = {"sword", "shield", "potion", "key", "scroll"}local totalItems = #inventory-- Calculate position based on percentage (results in decimal)local percentage = 0.75 -- 75% through the arraylocal calculatedIndex = percentage * totalItems-- Use math.floor to get valid array indexlocal actualIndex = math.floor(calculatedIndex)-- Ensure we have a valid index (Lua arrays start at 1)if actualIndex == 0 thenactualIndex = 1endprint("Calculated index: " .. calculatedIndex)print("Floored index: " .. actualIndex)print("Item at index " .. actualIndex .. ": " .. inventory[actualIndex])-- Another example with different percentagelocal lowPercentage = 0.2 -- 20% through the arraylocal lowIndex = math.floor(lowPercentage * totalItems)if lowIndex == 0 then lowIndex = 1 endprint("20% through array gives index: " .. lowIndex)print("Item: " .. inventory[lowIndex])
The output of this code will be:
Calculated index: 3.75Floored index: 3Item at index 3: potion20% through array gives index: 1Item: sword
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.
Example 3: Financial Calculations
This example demonstrates using math.floor() in financial calculations where monetary values need to be rounded down to avoid overcharging customers:
-- Financial calculation example - discount pricinglocal originalPrices = {29.99, 45.67, 12.34, 78.90}local discountRate = 0.15 -- 15% discountprint("Original Price -> Discounted Price (floored)")print("==========================================")for i = 1, #originalPrices dolocal originalPrice = originalPrices[i]-- Calculate discount amountlocal discountAmount = originalPrice * discountRate-- Calculate discounted pricelocal discountedPrice = originalPrice - discountAmount-- Use math.floor to round down to nearest cent-- Multiply by 100, floor, then divide by 100 for cents precisionlocal flooredPrice = math.floor(discountedPrice * 100) / 100print(string.format("$%.2f -> $%.2f", originalPrice, flooredPrice))end-- Calculate total savingslocal totalOriginal = 0local totalDiscounted = 0for i = 1, #originalPrices dototalOriginal = totalOriginal + originalPrices[i]local discountedPrice = originalPrices[i] * (1 - discountRate)local flooredPrice = math.floor(discountedPrice * 100) / 100totalDiscounted = totalDiscounted + flooredPriceendlocal totalSavings = totalOriginal - totalDiscountedprint("==========================================")print(string.format("Total Original: $%.2f", totalOriginal))print(string.format("Total After Floor Discount: $%.2f", totalDiscounted))print(string.format("Total Savings: $%.2f", totalSavings))
The output of this code will be:
Original Price -> Discounted Price (floored)==========================================$29.99 -> $25.49$45.67 -> $38.81$12.34 -> $10.48$78.90 -> $67.06==========================================Total Original: $166.90Total After Floor Discount: $141.84Total Savings: $25.06
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.
Example 4: Use Cases for Negative Numbers
This example shows how math.floor() behaves with negative numbers, which is crucial for understanding its mathematical definition:
-- Working with negative numberslocal negativeValues = {-2.3, -5.7, -10.1, -0.5}print("Understanding math.floor() with negative numbers:")print("================================================")for i = 1, #negativeValues dolocal value = negativeValues[i]local flooredValue = math.floor(value)print(string.format("math.floor(%.1f) = %d", value, flooredValue))end-- Comparison with positive equivalentsprint("\nComparison with positive numbers:")print("=================================")local testValues = {2.3, -2.3, 5.7, -5.7}for i = 1, #testValues dolocal value = testValues[i]local flooredValue = math.floor(value)if value > 0 thenprint(string.format("Positive: math.floor(%.1f) = %d", value, flooredValue))elseprint(string.format("Negative: math.floor(%.1f) = %d", value, flooredValue))endend
The output of this code will be:
Understanding math.floor() with negative numbers:================================================math.floor(-2.3) = -3math.floor(-5.7) = -6math.floor(-10.1) = -11math.floor(-0.5) = -1Comparison with positive numbers:=================================Positive: math.floor(2.3) = 2Negative: math.floor(-2.3) = -3Positive: math.floor(5.7) = 5Negative: math.floor(-5.7) = -6
Note: With negative numbers,
math.floor()rounds toward negative infinity, not toward zero. This means -2.3 becomes -3, not -2.
Frequently Asked Questions
1. What’s the difference between math.floor() and math.ceil()?
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.
2. Does math.floor() work with negative numbers?
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.
3. What happens if I pass an integer to math.floor()?
If you pass an integer to math.floor(), it returns the same integer unchanged. For example, math.floor(5) returns 5.
4. What happens if I pass a string to math.floor()?
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.
5. Is there a performance difference between math.floor() and other rounding methods?
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.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Lua on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Lua, a general-purpose programming language used for building games, web apps, and developer tools.
- Beginner Friendly.4 hours