Number and Currency Filters
Number and currency filters manipulate numbers. Common uses for number and currency filters include rounding numbers, displaying numbers as a variety of currency types, and formatting numbers by adding commas or other delimiters.
Let’s say you don’t want the cents displayed in the example from the previous lesson. Let’s add a currency_without_trailing_zeros filter to the mix:
Pamper your pet and save 25%! This week, our super-plush senior dog bed is just ${{ product.product_price | times: .75 | currency_without_trailing_zeros }}.
Pamper your pet and save 25%! This week, our super-plush senior dog bed is just $75.
Remember how we said filters are applied in order from left to right? The above is a great example: you want to put times: .75 first to do the mathematical calculation on the value, then add currency_without_trailing_zeros to remove the zeros from the result before our modified value is output.
Practice problem: number and currency filters
Let’s take another approach to displaying discounts with number and currency filters. Here’s the copy we want to display:
You get $20 off! The original price is $59.99, and you’ll only pay ___.
The key that contains the value is product.product_price. Use the subtract filter to remove $20 from the original price, the product.product_price key. Format the result as currency using the currency filter. (Assume your currency filter adds the currency symbol you’ve pre-selected plus two decimals.)
Select the right Liquid code from the options below to fill in the blank:
You get $20 off! The original price is $59.99, and you’ll only pay ___.
That’s not right; try again!
The correct answer is B or C (in this case, the order of operations doesn’t matter)!
Let’s run the code:
You get $20 off! The original price is {{ product.product_price | currency }}, and you’ll only pay {{ product.product_price | minus: 20 | currency }}.
You get $20 off! The original price is $59.99, and you’ll only pay $39.99.
Why don’t the other options work?
A) You must reference the entire key: product.product_price
D) The currency filter, as we’ve defined it for this problem, will always and only display two decimal points. Adding the extra colon, space, and integer may break your code.