我正在研究价格格式函数,它需要一个浮点数并正确表示它。为什么我不能链接String.replace?
ex。 190.5,应该是190,50
这就是我想出了
def format_price(price) do
price
|> to_string
|> String.replace ".", ","
|> String.replace ~r/,(\d)$/, ",\\1 0"
|> String.replace " ", ""
end
如果我运行下面。
format_price(299.0)
# -> 299,0
看起来它只是通过第一次替换。现在,如果我改变这以下。
def format_price(price) do
formatted = price
|> to_string
|> String.replace ".", ","
formatted = formatted
|> String.replace ~r/,(\d)$/, ",\\1 0"
formatted = formatted
|> String.replace " ", ""
end
然后,一切似乎工作得很好。
format_price(299.0)
# -> 299,00
这是为什么?
一般来说(对于那些稍后可能会阅读这些内容的人),当你通过函数传递参数时,确保你在你的参数中放置了括号。 –