Why can't I chain String.replace?

后端 未结 1 1339
生来不讨喜
生来不讨喜 2020-12-03 16:57

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



        
相关标签:
1条回答
  • 2020-12-03 17:14

    EDIT On the master branch of Elixir, the compiler will warn if a function is piped into without parentheses if there are arguments.


    This is an issue of precedence that can be fixed with explicit brackets:

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

    Because function calls have a higher precedence than the |> operator your code is the same as:

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

    Which if we substitute the last clause:

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

    And again:

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

    Should explain why you get that result.

    0 讨论(0)
提交回复
热议问题