我正在研究价格格式函数,它采用浮点数并正确表示.
恩.190.5,应该是190,50
这就是我提出的
def format_price(price) do
price
|> to_string
|> String.replace ".", ","
|> String.replace ~r/,(\d)$/, ",\\1 0"
|> String.replace " ", ""
end
Run Code Online (Sandbox Code Playgroud)
如果我运行以下.
format_price(299.0)
# -> 299,0
Run Code Online (Sandbox Code Playgroud)
看起来它只是通过第一次更换.现在,如果我将此更改为以下内容.
def format_price(price) do
formatted = price
|> to_string
|> String.replace ".", ","
formatted = formatted
|> String.replace ~r/,(\d)$/, ",\\1 0"
formatted = formatted
|> String.replace " ", ""
end
Run Code Online (Sandbox Code Playgroud)
然后一切似乎都很好.
format_price(299.0)
# -> 299,00
Run Code Online (Sandbox Code Playgroud)
为什么是这样?
elixir ×1