Divide a Money object / Money to Number

Highlighted
Shopify Partner
8 0 1

Is there a way of dividing the money object, or converting it to a Number to do the same?
I should precurse this with a note that I'm not familiar with Ruby, so I may be missing something obvious.

I'm trying to calculate the percentage a line price is of the total of the cart.
e.g line_item.line_price / cart.subtotal_price

But as per the scripts documentation the Money object doesn't have a divide method.

The scenario is that we want to offer a 20% discount, that maxes out at 500 dollars, after which the discount is a maximum of $100.

If there is a different approach to achieving that result other then shopify scripts, that would also be of great help.

e.g

  • T-Shirts 10 x 50 = $500
  • Pants    3 x 100 = $300
  • Total = $800
     
  • T-Shirt Line percentage of price = (500/800)*100 = 62.5%
  • Pants Line percentage of price = (300/800)*100 = 37.5%

Therefore out of a maximum of $100 the discounted price would be:

  • T-Shirts = $500 - $62.5 = $437.5
  • Pants = $300 - $37.5 = $262.5
  • Total = $700

Here is what the ideal scenario is if I could divide the money object:

if (Input.cart.discount_code)
  if (Input.cart.subtotal_price > (Money.new(cents: 100) * 500))
    
    cart_total = Input.cart.subtotal_price
    
    Input.cart.line_items.each do |line_item|

      line_price = line_item.line_price
      percentage_of_total = line_price / cart_total
      discount_of_line = percentage_of_total * 100

      line_item.change_line_price(line_price - discount_of_line, message: "Success")
    end
  else
    Input.cart.line_items.each do |line_item|
      line_price = line_item.line_price
      line_item.change_line_price(line_price * 0.8, message: "Success!")
    end
  end
end

Output.cart = Input.cart

 

Any help would be greatly appreciated :)

0 Likes
Highlighted
Explorer
66 0 28

Zoran - you can't divide money values, but you can multiply them by a fraction, eg:

a = Money.new(cents: 100)
b = a * (1.0 / 2.0)

As a fallback, you can also extract the number of cents from a Money object, perform calculations on that, and turn it back into a Money object:

a = Money.new(cents: 100)
b = Money.new(cents: (a.cents / 2))
Author of http://gavinballard.com/mastering-shopify-themes/ and http://bootstrapforshopify.com.
3 Likes
Highlighted
Shopify Partner
8 0 1

Hey Gavin.

Extracting the cents was exactly what I was looking for, and has solved the issue I was running into.

Thank you very much.

0 Likes