Round product discount price percantage to two digit numbers

Solved
Highlighted
New Member
2 0 0

Hello,
I'm trying to find a solution to round product discount to two digit numbers. 
As an example, we have this code that turns value into percentage

{{ product.price | times: -100 | divided_by: product.compare_at_price_max | plus: 100 | append: '%' }} 

This works great as I get the 34, 47, 58% values in product discount badge. However - what I'm trying to accomplish is to get a "10" out of every 11, 12, 13, 14, and "20" out of every 15, 16, 17, 18, 19.

I've tried adding round, floor, ceil and experiment with Shopify Math Filters with no real luck. Would you have any advices on how to approach this topic?

Thank you.

 

0 Likes
Highlighted
Shopify Expert
540 24 113

This is an accepted solution.

Try this:

 

{% assign discounted_price = product.price | times: 100.0 %}
{% assign original_price = product.compare_at_price | times: 1.0 %}
{% assign result = discounted_price | divided_by: original_price | divided_by: 10 | round: 0 | times: 10 %}
Discount: {{ 100.0 | minus: result }}%

Might be a little more complicated than necessary, but that's what I came up with for now ;)

The idea is to shift the decimal point to the left, then round off to zero decimal places and then shift the decimal point to the right, which rounds to the nearest multiple of 10.

★ ThemeUp: Nifty Upgrades for your Shopify Store ★ https://themeup.net
1 Like
Highlighted
New Member
2 0 0

Amazing! Thank you so much - that's fantastic - works as I imagined.
One thing I changed (to have 10% instead of 10.0%) is to remove 

{{ 100.0 | minus: result }}%

".0"
so the end result with that little tweak is 

{% assign discounted_price = product.price | times: 100.0 %}
{% assign original_price = product.compare_at_price | times: 1.0 %}
{% assign result = discounted_price | divided_by: original_price | divided_by: 10 | round: 0 | times: 10 %}
Discount: {{ 100 | minus: result }}%

And it gives me the correct percentage value :)

0 Likes
Highlighted
Shopify Expert
540 24 113

The .0 just causes the result to be formatted with decimals, so you can omit it to have an integer value. Which makes sense in your case as you want to have integer discount values.

 

 

★ ThemeUp: Nifty Upgrades for your Shopify Store ★ https://themeup.net
0 Likes
Highlighted
Tourist
9 1 2

Excuse the beginner question, but would this code apply rounding rules to a fixed amount discount that has been converted into another currency... so a store selling in USD with a fixed amount discount of $18 converted into GBP would show £14 being discounted instead of discounting the actual conversion of £13.52 for example (which is what happens currently when using Shopify's multi currency checkout)?

0 Likes