首页 > 解决方案 > Elixir - 当我在控制台中看到结果时出现字符串拆分问题

问题描述

我是 Elixir 的新手,我正在尝试在函数的参数中构建给定的浮点货币值并转换为具有 {integer: , decimal} 的对象当我将浮点值转换为字符串广告时拆分它..返回值很奇怪

我通过 iex 调用该函数,但我的拆分函数返回 ["4", "50"],它返回 450..

所以,我尝试打印 foo bar 示例,它返回 foobar 而不是 ["foo", "bar"]

这是代码:

def amountFormatter(amount) do
    stringAmount = Float.to_string(amount)
    splittedAmount = String.split(stringAmount, ".")
    IO.puts(String.split("foo bar", " "))
    integer = Enum.at(splittedAmount, 0)
    decimal = Enum.at(splittedAmount, 1) || 0
    amountFormatted = %{
      integer: Float.parse(integer),
      decimal: Float.parse(decimal)
    }
    amountFormatted
  end

在此处输入图像描述

标签: splitelixir

解决方案


当您将列表传递给 时IO.puts/2,该列表被视为chardata。本质上,它连接列表中的所有内容。

iex> IO.puts(["foo", "bar"])
foobar # printed
:ok # returned

要在运行代码时检查值,最好使用IO.inspect/2

iex> IO.inspect(["foo", "bar"])
["foo", "bar"] # printed
["foo", "bar"] # returned

推荐阅读