Skip to main content
0 reactions

How to Use the floor Function in OpenTofu

Card titled The floor Function, labelled OpenTofu Functions, showing floor(5.9) and the result 5.
Round a number down to a whole number with OpenTofu’s floor function

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

SyntaxHCL
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

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:

TerminalBash
tofu console

Type each expression to see the result:

tofu consolePlain text
> 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

MistakeWhat happensDo this instead
Expecting floor(-1.5) to be -1It’s -2: floor always rounds down.Use ceil to round up.
Accepting 80.5 as a port numbervar.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