elixir - 在 Elixir 中将数字转换为单词

标签 elixir

是否有一个库可以将数字转换为单词?
例如:
转换 103 -> 103
或者 转换 5765 -> 五千七百六十五

最佳答案

未发布到 Hex.pm,但 here's a gist实现数字到单词算法的模块:

iex(2)> NumberToWord.say(123312133123)
"one hundred and twenty three billion, three hundred and twelve million, one hundred and thirty three thousand, one hundred and twenty three"

来源:

defmodule NumberToWord do
  @spec say(integer) :: String.t
  def say(n), do: n |> say_io() |> IO.iodata_to_binary()

  @spec say_io(integer) :: iodata
  def say_io(1), do: "one"
  def say_io(2), do: "two"
  def say_io(3), do: "three"
  def say_io(4), do: "four"
  def say_io(5), do: "five"
  def say_io(6), do: "six"
  def say_io(7), do: "seven"
  def say_io(8), do: "eight"
  def say_io(9), do: "nine"
  def say_io(10), do: "ten"
  def say_io(11), do: "eleven"
  def say_io(12), do: "twelve"
  def say_io(13), do: "thirteen"
  def say_io(14), do: "fourteen"
  def say_io(15), do: "fifteen"
  def say_io(16), do: "sixteen"
  def say_io(17), do: "seventeen"
  def say_io(18), do: "eighteen"
  def say_io(19), do: "nineteen"
  def say_io(20), do: "twenty"
  def say_io(30), do: "thirty"
  def say_io(40), do: "forty"
  def say_io(50), do: "fifty"
  def say_io(60), do: "sixty"
  def say_io(70), do: "seventy"
  def say_io(80), do: "eighty"
  def say_io(90), do: "ninety"
  def say_io(n) when n < 100 do
    tens = div(n, 10) * 10
    remainder = rem(n, 10)
    format(tens, "", " ", remainder)
  end
  def say_io(n) when n < 1000 do
    hundreds = div(n, 100)
    remainder = rem(n, 100)
    format(hundreds, " hundred", separator(remainder), remainder)
  end
  ~w[thousand million billion trillion quadrillion quintillion sextillion septillion octillion nonillion decillion]
  |> Enum.zip(Stream.unfold(1000, fn acc -> {acc, acc * 1000} end))
  |> Enum.each(fn {suffix, m} ->
    def say_io(n) when n < (unquote(m) * 1000) do
      number = div(n, unquote(m))
      remainder = rem(n, unquote(m))
      format(number, " " <> unquote(suffix), separator(remainder), remainder)
    end
  end)

  @spec separator(integer) :: String.t
  def separator(remainder) when remainder < 100, do: " and "
  def separator(_remainder), do: ", "

  @spec format(integer, String.t, String.t, integer) :: iodata
  def format(number, illion, _separator, 0), do: [say_io(number) | illion]
  def format(number, illion, separator, remainder), do: [say_io(number), illion, separator | say_io(remainder)]
end

关于elixir - 在 Elixir 中将数字转换为单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45399578/

相关文章:

string - 在 Elixir 中解析字符串

混合键 Elixir map

postgresql - Ecto 构建多个关联

json - Phoenix Ecto 如何处理 NoResultsError

erlang - 了解 Elixir badarg 错误消息

elixir - 谁能准确解释一下Plug.Conn中put_private的含义?

elixir - 从 github 导入 Elm 前端到 Phoenix 后端

elixir - 对 iex shell 中的输入进行着色

erlang - Elixir - https URL 的问题

elixir - 是否可以在 elixir 中的流上运行 reduce?