Twig math with number_format filter

Is there a way to utilize the twig number_format filter on math operations?

For example, the following will format “2000” into “2,000”

${{ 2000|number_format }}

I’ve tried a number of way to get this to work with looper fields which are performing math functions but haven’t had any luck to add commas to the results of the following with placing “number_format” anywhere:

${{{{dc:looper:field key="road_trip_cost"}} - {{dc:looper:field key="shipping_cost"}}}}

Thanks!

Hello @bangak,

Thank you for the inquiry.

Based on https://twig.symfony.com/doc/3.x/filters/number_format.html, you can try this:

${{ (dc:looper:field('road_trip_cost') - dc:looper:field('shipping_cost')) | number_format(2, '.', ',') }}

Make sure that Advanced is enabled in the Twig extension.

Let us know the result.

Best regards.

Thanks for your help! I’m getting the following error after enabling advanced in the Twig extension and using your suggest code:

An opened parenthesis is not properly closed. Unexpected token "punctuation" of value ":" ("punctuation" expected with value ")") in "${{ (dc:looper:field('road_trip_cost') - dc:looper:field('shipping_cost')) | number_format(2, '.', ',') }}

I also tried the following which didn’t cause an error but broke the calculation and didn’t add a comma as intended. The output was simply substracting 1 from the first field rather than pulling in the actual value of shipping_cost.

${{ {{dc:looper:field key="road_trip_cost"}} - {{dc:looper:field key="shipping_cost"}} | number_format(2, '.', ',')}}

Removing the math operator and second filed as follows outputs the number correctly so it’s just the math portion that seems to be tripping things up. Results of below takes “3150” and outputs “3,150”

${{ {{dc:looper:field key="road_trip_cost"}} | number_format}}

Thank you for the update. We may need to login to properly check the dynamic content. Please create a test page and provide the login details in the secure note.

Thank you again! The requested details have been added to my prior message.

Thank you for the info. We adjusted the template on one of the headline elements.

{% set roadTripCost = looper.field({"key":"road_trip_cost"}) %}
{% set shippingCost = looper.field({"key":"shipping_cost"}) %}
{% set total = roadTripCost - shippingCost %}
${{ total | number_format(2, ".", ",") }}

Let us know if you need more info.

Brilliant, thanks! For anyone wondering in the future, the first number in the parentheses represents the decimals places. To get this to omit them entirely you can use 0, like such:
{{ total | number_format(0, ".", ",") }}

This will then print $1,635, just as I was hoping.

Glad we could be of help! Feel free to open another thread if you have more questions. Have a nice day.