<p>You can use PHP's sprintf function via [the format filter in Twig].<a href="https://twig.symfony.com/doc/2.x/filters/format.html" rel="noreferrer">1</a></p>

<p>So to add a leading zero to single digit numbers:</p>

<p><code>{{ "%02d"|format('4') }}</code></p>

<p>Which would return <code>04</code></p>

<hr>

<p>Or in your case <code>{{ "%02d"|format(entry.episodeNumber) }}</code></p>

CC BY-SA 4.0
2018-12-29T15:09:47.120Z
2018-12-29T15:09:47.120Z
James Greig
<p>There aren't any filters built in to Craft (or Twig) that does this, but your <code>{% if %}</code> conditional could be trimmed down to a single-line <em>ternary operation</em>:</p>

<pre><code>{% set episodeNumber = (entry.episodeNumber &lt; 10 ? '0') ~ entry.episodeNumber %}
</code></pre>

<p>or even</p>

<pre><code>&lt;span&gt;{{ (entry.episodeNumber &lt; 10 ? '0') ~ entry.episodeNumber }}&lt;/span&gt;
</code></pre>

CC BY-SA 4.0
2018-12-26T16:09:36.527Z
2018-12-28T11:09:36.240Z
2018-12-28T11:09:36.240Z
Mats Mikkel Rummelhoff
<p>I have a number field used for episode numbers and I would like to automatically add a leading zero when the number is less than 10. I have this working with a conditional but it seems inefficient. Is there a twig filter that I don't know about that does this?</p>

<pre><code>{% if entry.episodeNumber &lt; "10" %}
    {% set episodeNumber = '0' ~ entry.episodeNumber %}
{% else %}
    {% set episodeNumber = entry.episodeNumber %}
{% endif %}
</code></pre>

<p>The above works but seems overly long to accomplish what should be a simple task.</p>

<templating>
Add a Leading Zero with a number field
# Add a Leading Zero with a number field

(Asked by: username_0 on 2018-12-26)

I have a number field used for episode numbers and I would like to automatically add a leading zero when the number is less than 10. I have this working with a conditional but it seems inefficient. Is there a twig filter that I don't know about that does this?
{% if entry.episodeNumber < "10" %}
    {% set episodeNumber = '0' ~ entry.episodeNumber %}
{% else %}
    {% set episodeNumber = entry.episodeNumber %}
{% endif %}

The above works but seems overly long to accomplish what should be a simple task.

**Tags:** templating


---

## 2 answers

### Answer by username_2 on 2018-12-26. Score: 7 | Accepted answer

There aren't any filters built in to Craft (or Twig) that does this, but your {% if %} conditional could be trimmed down to a single-line ternary operation:
{% set episodeNumber = (entry.episodeNumber < 10 ? '0') ~ entry.episodeNumber %}

or even
{{ (entry.episodeNumber < 10 ? '0') ~ entry.episodeNumber }}


---

### Answer by username_1 on 2018-12-29. Score: 7

You can use PHP's sprintf function via [the format filter in Twig].[1](https://twig.symfony.com/doc/2.x/filters/format.html)

So to add a leading zero to single digit numbers:

`{{ "%02d"|format('4') }}`

Which would return `04`

---

Or in your case `{{ "%02d"|format(entry.episodeNumber) }}`


---

