Terraform: 3 ways to round a number

Updated: February 3, 2024 By: Guest Contributor Post a comment

Introduction

When working with Terraform, you might find yourself in need of rounding numbers to meet the requirements of your infrastructure’s configuration. Though Terraform does not offer a plethora of built-in functions specific for all possible rounding scenarios, it provides enough flexibility through its basic math functions and workarounds. This post explores several strategies to round numbers in Terraform, offering step-by-step solutions and complete code examples.

Floor() Function

The floor() function rounds a number down to the nearest whole number. It is straightforward and useful for ensuring an output is not greater than a certain value.

Use the floor function directly on the number you want to round down is as simple as this:

output "rounded_down" {
  value = floor(5.7)
}

Output: 5

Notes: This method is useful for scenarios where it’s acceptable or desired to round down. It’s deterministic and performance-efficient since it’s a direct built-in function.

Ceil() Function

Similar to the floor function, the ceil (ceiling) function rounds a number up to the nearest whole number. This method ensures your output is not less than a certain value.

Use the ceil function on the number you intend to round up:

output "rounded_up" {
  value = ceil(5.3)
}

Output: 6

Notes: The ceil function is perfectly suited for cases where rounding up is necessary. It’s also deterministic and provides simplicity and performance efficiency.

Arithmetic Rounding

This method rounds to the nearest whole number, either up or down, based on the decimal part. If the decimal is 0.5 or above, it rounds up; otherwise, it rounds down.

  1. Add 0.5 to your number.
  2. Use the floor function on the result.

Example:

output "arithmetically_rounded" {
  value = floor(5.7 + 0.5)
}

Output: 6

Notes: Arithmetic rounding is closer to the rounding logic most people use in daily life. However, it doesn’t directly handle situations where you always want to round down when at exactly 0.5.

Conclusion

In Terraform, while there are no functions specifically named after the rounding concepts as understood in traditional programming languages, the combination of basic mathematical functions such as floor and ceil, along with simple arithmetic operations, offers a powerful toolkit for numerical manipulation. By understanding and utilizing these methods, Terraform users can effectively manage numerical rounding as required by their infrastructure needs. Remember, the choice of method depends largely on the specific needs of your configuration and the desired direction of rounding.