Math Filters
Math filters do mathematical operations on numbers. Number values contain either integers (numbers without decimal points, like 2) or floats (numbers with decimal points, like 2.5). You can use math filters to do arithmetic calculations (like adding, subtracting, or dividing the value of a numeral) or change how numbers are displayed (like rounding a float up to the nearest integer).
For instance, you could use the times filter to show the price of a product after a discount if you’re running a promotion—let’s say 25% off a $100 item. Here’s what that might look like:
Pamper your pet and save 25%! This week, our super-plush senior dog bed is just ${{ product.product_price | times: .75 }}.
Pamper your pet and save 25%! This week, our super-plush senior dog bed is just $75.00.
Pro tip: filters are applied to your key in order from left to right. That means you can do some snazzy math, but you’ll need to pay attention to the order in which you list your filters.
Practice problem: math filters
Now let’s flex our math filter muscles to keep our discounted prices looking neat and tidy. Here’s the copy we want in the email:
Two-thirds off our newest senior dog vitamin sample—a $10 value for only $____
The key that contains the value is product.product price. Use the times filter (multiplies the value by a number) and round filter (rounds a number to the nearest integer or a specified number of decimals) to fill in the reduced product price.
Hint: to specify the number of decimals for the round filter, add a colon, a space, and the number of decimals to which you want to round.
Select the right Liquid code from the options below to fill in the blank:
Two-thirds off our newest senior dog vitamin sample—a $10 value for only $____
That’s not right; try again!
The correct answer is B!
Let’s run the code:
Two-thirds off our newest senior dog vitamin sample—a ${{ product.product_price }} value for only ${{ product.product_price | times: .33 | round: 2 }}
Two-thirds off our newest senior dog vitamin sample—a $10 value for only $3.30
Why don’t the other options work?
A) It doesn’t specify the number of decimal places to which you want to round, so the filter will round to the nearest integer. The result using this code would be $3
C) Math error—the price should be reduced by two-thirds, leaving one-third left. The result using this code would be $6.60
D) The order of operations is incorrect—the rounding is done first and then the discount is applied. The result using this code would be $3.3