2

I am trying to get Liquid to simply round up a number. Here is my code:

{% assign loopCount = page.boxCount | plus:0  | divided_by:3 | %}
{{ loopCount | ceil }}

In this case loopCount = 4. I can confirm it is a number by adding to it and displaying the results.

{% assign loopCount = page.boxCount | plus:0  | plus:3.5 %}
{{ loopCount }}

Displays 7.5

However, when I divide by 3, which should be 1.333... my display shows 1. Liquid seems to be automatically rounding down.

What I need it to do is round up so I get 2. What code should I use to get the expected results?

Thanks

Edit: I should note I am aware of ceil, but I can't use that unless my number is actually a decimal.

PruitIgoe
  • 6,166
  • 16
  • 70
  • 137

1 Answers1

2

When you divide by an integer, the result will be an integer. If you want to get a float, divide by a float (see "Controlling rounding" from: https://shopify.github.io/liquid/filters/divided_by/):

require 'liquid'

source = <<-SRC
{% assign loopCount = page.boxCount | divided_by:3.0 %}
loopCount = {{ loopCount }}
loopCount | ceil = {{ loopCount | ceil }}
SRC

@template = Liquid::Template.parse(source)

puts @template.render('page' => {'boxCount' => 4 })

results in:

loopCount = 1.3333333333333333
loopCount | ceil = 2

And if you do:

require 'liquid'

source = <<-SRC
{% assign loopCount = page.boxCount | divided_by:3 %}
loopCount = {{ loopCount }}
loopCount | ceil = {{ loopCount | ceil }}
SRC

@template = Liquid::Template.parse(source)

puts @template.render('page' => {'boxCount' => 4 })

you get:

loopCount = 1
loopCount | ceil = 1
Bart Kiers
  • 166,582
  • 36
  • 299
  • 288