gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:51:04 31 4
gpt4 key购买 nike

是否有一个库可以将数字转换为单词?
例如:
转换 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com