2015-09-16 69 views
30

我正在研究价格格式函数,它需要一个浮点数并正确表示它。为什么我不能链接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 

这是为什么?

+4

一般来说(对于那些稍后可能会阅读这些内容的人),当你通过函数传递参数时,确保你在你的参数中放置了括号。 –

回答

28

编辑在Elixir的主分支上,编译器会警告函数是否在没有括号的情况下传递,如果有参数的话。


这是优先级的问题,可以固定明确的括号:

price 
|> to_string 
|> String.replace(".", ",") 
|> String.replace(~r/,(\d)$/, ",\\1 0") 
|> String.replace(" ", "") 

因为函数调用具有比|>操作的优先级高的代码是一样的:

price 
|> to_string 
|> String.replace(".", 
    ("," |> String.replace ~r/,(\d)$/, 
    (",\\1 0" |> String.replace " ", ""))) 

如果我们替代最后一项:

price 
|> to_string 
|> String.replace(".", 
    ("," |> String.replace ~r/,(\d)$/, ".\\10")) 

并再次:

price 
|> to_string 
|> String.replace(".", ",") 

需要说明为什么你得到这一结果。

+0

@Gazler,你有链接到介绍改变的提交吗? – asymmetric

+1

@asymmetric https://github.com/elixir-lang/elixir/commit/3487d00ddb5e90c7cf0e65d03717903b9b27eafd – Gazler

相关问题