Personalized checkout and custom promotions with Shopify Scripts
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.
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.
User | RANK |
---|---|
4 | |
2 | |
2 | |
1 | |
1 |
On our Shopify Expert Marketplace, you can find many trusted third party developers and fr...
By Arno Nov 27, 2023You've downloaded the Search & Discovery app from the Shopify App store, and as you're ...
By Skye Nov 8, 2023The year-end shopping season is just around the corner. Is a flash sale on your radar? Are...
By Jasonh Nov 6, 2023