round is a Jinja2 filter, used to commonly used to round up or round down an integer. In this example, 1.7 will be rounded.
---
- hosts: localhost
tasks:
- name: round 1.7
debug:
msg: "{{ 1.7 | round }}"
...
Which should return 2.0.
TASK [round 1.7]
ok: [localhost] => {
"msg": "2.0"
}
Round accepts two arguments. The first argument is the precision and the second argument is the rounding method to use. When no arguments are specified, the precision is 0 and the method is common, like this.
---
- hosts: localhost
tasks:
- name: round 2.4 common
debug:
msg: "{{ 2.4 | round(0, 'common') }}"
...
Which should return 2.0.
TASK [round 1.7 common]
ok: [localhost] => {
"msg": "2.0"
}
The precision argument tells round how many decimals to round.
---
- hosts: localhost
tasks:
- name: round 2.45 common
debug:
msg: "{{ 2.45 | round(1, 'common') }}"
...
Which should return 2.5.
TASK [round 2.45 common]
ok: [localhost] => {
"msg": "2.5"
}
The second argument is the rounding method, which can be common (either round up or down), ceil (always round up) or floor (always round down). In this example, 1.77 will be rounded down.
---
- hosts: localhost
tasks:
- name: round 1.67 down
debug:
msg: "{{ 1.67 | round(1, 'floor') }}"
...
Which should return 1.7.
TASK [round 1.67 down]
ok: [localhost] => {
"msg": "1.6"
}
Notice that round returns a decimal. If you want to return a whole number, you can pipe through the int filter, like this.
- hosts: localhost
tasks:
- name: round 1.67123 to a whole number
debug:
msg: "{{ 1.67123 | round | int }}"
...
Which should return a whole number.
TASK [round 1.67123 to a whole number]
ok: [localhost] => {
"msg": "2"
}
If you are adding, subtracting, multiplying or dividing and want to return a whole number, put the math inside of parenthesis.
---
- hosts: localhost
tasks:
- name: round to a whole number
debug:
msg: "{{ ((11.7 - 4.765) * 3.92) | round | int }}"
...
Which should return a whole number.
TASK [round to a whole number]
ok: [localhost] => {
"msg": "27"
}
Let's say you are using the vars plugin to create a variable. In this example, the foo variable contains a value of 1.7. Notice in this example that the value is not wrapped in quotes. If the value were wrapped in quotes, the value would be interpreted as a string, not an integer.
vars:
foo: 1.7
Here is how you would round the foo variable. Notice that foo is not wrapped in quotes, so that foo is interpreted as a variable, not a string.
---
- hosts: localhost
tasks:
- name: round the 'foo' variable
debug:
msg: "{{ foo | round }}"
...
The following should be returned.
TASK [round the 'foo' variable]
ok: [localhost] => {
"msg": "2.0"
}
Did you find this article helpful?
If so, consider buying me a coffee over at