CircularRecursion
CircularRecursion

Reputation: 460

Only show decimal for non-integers in Liquid

Pretty simple one I think, but can't work out if it is possible. I have a number in a Liquid template that should only have a decimal place if it isn't an integer. Unfortunately the database stores a float (which I cannot change), so my only option is to try do this in Liquid. Essentially if the number is 5.5 I want it to output that. However it the number is 5.0 I want it to output 5.

I can't see a way of checking whether a number is a float or not. Ideas?

Upvotes: 0

Views: 2051

Answers (1)

David Mc
David Mc

Reputation: 119

This could be achieved by using some of the liquid filters.

First you use split to break the number up by the decimal point, then last to check if the last number is 0. Finally use remove to get rid of the .0.

For example:

{% assign result = 5.0 %}
{% assign splitResult = result | split: '.' %}
{% if splitResult.last == '0' %}
  {% assign newResult = result | remove: '.0'  %}
{% else %}
  {% assign newResult = result %}
{% endif %}

{{ newResult}}

In this case {{ newResult }} will output 5.

Hope that helps!

Upvotes: 3

Related Questions