Take the 2-minute tour ×
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It's 100% free, no registration required.

Say I have {{ item.width }} and {{ item.height }} which are number fields with 2 decimal places.

In my template I have this:

<p>Dimensions: {{ item.width }} x {{ item.height }} in.</p>

Which will output like this:

Dimensions: 8.50 x 11.00 in.

Dimensions: 5.00 x 7.00 in.

Dimensions: 4.25 x 6.50 in.

How would I drop the decimal places that are not used? Like this:

Dimensions: 8.5 x 11 in.

Dimensions: 5 x 7 in.

Dimensions: 4.25 x 6.5 in.

share|improve this question

2 Answers 2

up vote 5 down vote accepted

This can be done with Twig's trim filter. It works just like PHP's trim function.

{{ item.width|trim('0')|trim('.') }}
share|improve this answer
    
Dammit, you're too fast. I had the link to trim ready and everything. Wouldn't trim('0') suffice? –  Matt Stein Jun 27 at 18:10
    
That does not really work, if I have an entry with '10' in the number field it will output 10.00 but when I add the trim it outputs '1'. I don't think I can trust the client to always enter it as '10.00' and not '10' –  pixelJitsu Jun 27 at 18:15
    
@pixelJitsu Which doesn't work? trim('.0'), trim('0'), or both? This should totally be an output thing, no way you should have your clients remember to enter numbers a certain way! –  Matt Stein Jun 27 at 18:18
1  
Ah. Good catch. Then we do it in phases. Answer Updated. –  Bryan Redeagle Jun 27 at 18:21
1  
Twig is so cool. Thanks –  pixelJitsu Jun 27 at 18:26

I would use the twig number_format filter to make sure there were a known number of decimal places, then trim first the 0s, then the '.':

{{item.width|number_format(4)|trim('0')|trim('.')}}

I would write a macro for this:

{% macro num_format(n) %}
  {{n|number_format(4)|trim('0')|trim('.')}}
{% endmacro %}

Called like so:

{{ num_format(item.width) }}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.