How can I format decimals with trailing zeros in discount messages?

Shopify Partner
1 0 0


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)

Shopify Partner
19 2 6



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



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.