floor rounds a number down to the closest whole number at or below it. Comparing a number with its floor tells you whether it’s whole, which is handy for settings such as a port.
Syntax
floor(<NUMBER>)
<NUMBER>: any number, which may have a fraction. Negative numbers round down too, away from zero.
The function is described in floor Function (opens in a new tab) in the OpenTofu® docs.
Prerequisites
- OpenTofu installed. Installing OpenTofu (opens in a new tab) in the OpenTofu docs covers every system.
Step 1: Try It in tofu console
Open a terminal in any empty folder and start tofu console, which evaluates expressions as you type them:
tofu console
Type each expression to see the result:
> floor(5.9)
5
> floor(-1.5)
-2
> floor(8080) == 8080
true
> floor(80.5) == 80.5
false
> exit
Clean Up
Type exit to leave the console. The example creates nothing, so there’s nothing else to remove.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Expecting floor(-1.5) to be -1 | It’s -2: floor always rounds down. | Use ceil to round up. |
| Accepting 80.5 as a port number | var.port is a number, so a fraction passes the type check. | Add a check: floor(var.port) == var.port. |
FAQ
How do I round to the nearest whole number?
OpenTofu has no round function; floor(x + 0.5) does it for positive numbers.
Does floor change the type?
No. The result is still a number.
Conclusion
floor(<NUMBER>) rounds down to a whole number, and floor(x) == x checks that a number has no fraction.
Additional Resources
OpenTofu® is a registered trademark of LF Projects, LLC. Other names mentioned are trademarks of their respective owners. JD Bots isn’t affiliated with or endorsed by the OpenTofu project.
0 comments