Money formatting in discount message

digital-cake
Shopify Partner
1 0 0

Hello,

Does anyone know a way to format a decimal amount to display as a string with 2 trailing zeros. For example if the discount decimal amount is 32.9 how could we get this to display in the discount message string as 32.90?

I have tried functions normally available to Ruby such as sprintf and even using the modulo operator but it seems the modified version of Ruby used in the Script Editor doesn't allow the Decimal type to use the modulo operator and sprintf is unavailable.

Hope someone can help anyway.

Reply 1 (1)
Stephen2020
Shopify Partner
10 1 4

Hi,

 

at first glance you think it can't be that difficult, but you're right. In Shopify, it doesn't seem to be that easy.

 

Without the %-operator and without the format or sprintf command, I think it will become necessary to write a helper method.

 

I've just written such a helper. My suggestion is to extend the Float class with a method "To decimal place string" (to_dp_s) as follows.

 

 

class Float
  def to_dp_s(dp)
    dp = 0 if dp < 0
    s = (self * 10**dp).round.to_s
    s.rjust([dp + 1, s.length].max, "0").insert((dp + 1) * -1, '.') if dp > 0
  end
end

 

 

Let us assume that you have an arbitrary number in a variable named "amt", and you want to display that value in the discount message. Then the code could look as follows.

 

amount = Float(amt.to_s).to_dp_s(2)
line_item.change_line_price(..., message: "Discount $#{amount} for xyz")

 

If amt is set to 32.9 it will be displayed as 32.90 then.

 

Hope that you will find this usefull.