Calculate percentage of total cart

Huphsi
New Member
2 0 0

I'm trying to convert a discount with a total amount into the corresponding percentage of the whole cart. Afterwards i want to apply this percentage to each item of the cart - so the total discount on the cart will be the same as the initial discount (total amount).

a = Money.new(cents: 100)
puts (a.cents / 2) # works
# => 50
puts (50 / a.cents) # doesn't work: [Error] non float value

In order to get the total amount of cart i extract it and use the cents for the calculation. Unfortunately i get the following error message (as you can see in the code snippet). I can't find a way to convert the "money.cents" into a real float. 

0 Likes
Alex
Shopify Staff
Shopify Staff
1555 81 294

Hey Huphsi.

Can you be clear about what gems or libraries you're using to accomplish this? You're likely going to have more success in the Money gem you're drawing this class from, even if it's overloaded in one of our libraries.

Cheers.

0 Likes
Huphsi
New Member
2 0 0

Hi Alex,

just using the plain Shopify Scripts environment without any additional gems / libraries so far.

Also just realized i posted my question in the wrong subforum - should be posted in "Script Editor App".
Any chance you can move it there? Otherwise i can also just reopen a copy there?

Thanks for your help!

0 Likes
Alex
Shopify Staff
Shopify Staff
1555 81 294

Hey! Good observation, I'll move this right over there. Cheers!

0 Likes
Mandelbrotian
Shopify Partner
132 1 19

Hi Huphsi,

You can circumvent this with a little work around, it's not kosher but it'll do the trick until they fix the bug.

Just convert the Decimal to a string, and then to an Int with

a = Money.new(cents: 100)
a_int = Integer(a.cents.to_s)
puts (50 / a.cents) #doesn't work
puts (50 / a_int) #works

Hope that helps.

Cheers,

Elliott

Feeling a bit lost? Contact elliot@mandelbrotian.com for help with theme setup, alterations, custom functionality, and app development.