Ansible - Round an integer up or down using the round filter

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.

- name: "round integer"
  debug: 
    msg: "{{ 1.7 | round }}"

 

Which should return 2.0.

TASK [round integer]
ok: [server1.example.com] => {
    "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.

- name: "round integer"
  debug: 
    msg: "{{ 1.7 | round(0, 'common') }}"

 

The precision argument tells round how many decimals to round. In this example, 1.77 will be rounded.

- name: "round integer"
  debug: 
    msg: "{{ 1.77 | round(1) }}"

 

Which should return 1.8.

TASK [round integer]
ok: [server1.example.com] => {
    "msg": [
        "1.8"
    ]
}

 

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.

- name: "round integer"
  debug: 
    msg: "{{ 1.77 | round(1, 'floor') }}"

 

Which should return 1.7.

TASK [round integer]
ok: [server1.example.com] => {
    "msg": [
        "1.7"
    ]
}

 

Notice that round returns a decimal. If you want to return a whole number, you can pipe through the int filter, like this.

- name: "round integer to a whole number"
  debug: 
    msg: "{{ 1.7 | round | int }}"

 

Which should return 2.

TASK [round integer to a whole number]
ok: [server1.example.com] => {
    "msg": [
        "2"
    ]
}

 

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.

- name: "round the 'foo' variable"
  debug:
    msg: "{{ foo | round }}"

 

The following should be returned.

TASK [round the 'foo' variable]
ok: [server1.example.com] => {
    "msg": [
        "2.0"
    ]
}


Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.





Please enter 9e715 in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |