I'm working on a price format function, which takes a float, and represent it properly.
ex. 190.5, should be 190,50
This is what i came up with
def format_price(price) do
price
|> to_string
|> String.replace ".", ","
|> String.replace ~r/,(d)$/, ",\1 0"
|> String.replace " ", ""
end
If i run the following.
format_price(299.0)
# -> 299,0
It looks like it only ran through the first replace. Now if i change this to the following.
def format_price(price) do
formatted = price
|> to_string
|> String.replace ".", ","
formatted = formatted
|> String.replace ~r/,(d)$/, ",\1 0"
formatted = formatted
|> String.replace " ", ""
end
Then everything seems to work just fine.
format_price(299.0)
# -> 299,00
Why is this?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…