5

I'm outputting prices in a channel with a little formatting like so:

£{{ entry.priceFrom|number_format(2,'.',',') }}

Gives me £1,000.00 or £99.99 etc... However client isn't a fan of the double zeros (e.g. £100.00) and would prefer such prices to show up as £100 – only showing decimal numbers if they're not "00".

I was working on some kind of preprocessing/condition here but it seems long-winded, and wondered if anyone has a neat solution?

12

Craft comes with a currency filter that makes this pretty easy – you don’t even need the £:

{{ entry.priceFrom|currency('GBP', true) }}

The 'GBP' establishes the currency (so the price is prefixed with £), and passing true to the second argument tells Craft to strip out the cents from the formatted string if there aren’t any (so £100 instead of £100.00).

  • Wow, great thanks. – Ian Ebden Oct 6 '15 at 9:16
3

How about something like:

£{{ 1000.00 | number_format(2,'.',',') | replace({".00" : ""}) }}

gives:

£1,000

Got a similar idea from How would I omit zero value decimals in a number format?.

2

Just for future reference, Craft 3 is a little different with the currency filter.

{{ entry.price|currency('CAD', stripZeros = true) }}
  • Would you mind explaining what makes your answer different than Brandons? – Robin Schambach Apr 2 '18 at 12:59
  • @RobinSchambach I tried using this one ('CAD', true) in my new Craft 3 build and was getting an error. So you have to use this ('CAD', stripZeros = true) for it to work in Craft 3 – mateostabio Apr 2 '18 at 22:44
1

Well I've got this working with:

{% set decimal = entry.priceFrom|reverse|slice(1,2) %}

{% if decimal == "0" %}{{ entry.priceFrom|number_format(0,'.',',') }}{% else %}{{ entry.priceFrom|number_format(2,'.',',') }}{% endif %}

Basically I'm reversing the string so I can check for a zero at the end (or not). It's fairly clean, but if anyone can improve on it I'd love to hear.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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