为什么我不能链接String.replace?

时间:2015-09-16 17:53:30

标签: elixir

我正在研究价格格式函数,该函数采用浮点数并正确表示。

离。 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

为什么会这样?

1 个答案:

答案 0 :(得分:30)

编辑在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(".", ",")

应该解释为什么会得到这个结果。

相关问题