ansible how to get last 2 digit of number

Viewed 559

I have question about how to convert a digit to string and then get last 2 number using filter

For string, it's easy to use like:

vars:
  string_1: 'abcd'
  number_1: 1234

For string, it's easy:

"{{ string_1[-2:] }}"

But for number then i have to convert to string first but it failed while templating.

"{{ number_1 | string | [-2:] }}

How can I achieve this in single line code?

2 Answers

Close the conversion in parenthesis. The index has higher precedence compared to the filter. (And index can't be used as a filter, of course).

msg: "{{ (number_1|string)[-2:] }}"

The only difference is that modulus % returns an integer. The tasks

    - debug:
        msg: "{{ (number_1 % 100)|type_debug }}"
    - debug:
        msg: "{{ (number_1|string)[-2:]|type_debug }}"

give

    "msg": "int"
    "msg": "str"

You may use a modulus trick here:

{{ number_1 % 100 }}

The modulus dividing by 100 should yield the final two digits of any number input.

Related