Math: Round, Ceiling, Floor

Are there tools built into the Math module to handle rounding a number, finding the ceiling of a number, or finding the floor of a number?

Hi @nadesignlab ,

Yes, all three are built into the Math tag:

<Math>round(2.5)</Math>          <!-- 3 -->
<Math>round(3.14159, 2)</Math>   <!-- 3.14 -->
<Math>ceil(2.1)</Math>           <!-- 3 -->
<Math>floor(2.9)</Math>          <!-- 2 -->

round takes an optional second value for the number of decimal places. A negative value rounds to tens, hundreds and so on, so round(1234.5678, -2) gives 1200.

ceil and floor take one value and always return a whole number. To round up or down to a number of decimal places, multiply first and then divide:

<Math>ceil(2.341 * 100) / 100</Math>   <!-- 2.35 -->
<Math>floor(2.349 * 100) / 100</Math>  <!-- 2.34 -->

They also work with math variables and with other tags inside the expression:

<Set math=total>19.999</Set>
<Math>round(total, 2)</Math>

Tip for decimals: depending on the server’s PHP settings, a decimal result can print with extra digits, like 3.1400000000000001. Wrapping it in the Format tag always gives clean output:

<Format number decimals=2><Math>round(total, 2)</Math></Format>

You can add thousands="," for a thousands separator too. See Format → Number and the Math module docs.

One thing to watch for: ceil and floor only take one value. In versions before 4.3.2, giving them a second one (ceil(2.1, 2)) caused a critical error on the page. That’s fixed in 4.3.2, so if you’re on an older version, updating is worth it.