gpt4 book ai didi

ruby-on-rails - 在 ruby​​ on Rails 中将数字转换为单词

转载 作者:行者123 更新时间:2023-12-02 10:55:52 24 4
gpt4 key购买 nike

我知道某处有一颗 gem 。尝试在没有 gem 的情况下实现它。我只需要数字到英文单词的整数。找到了这个,但是非常困惑。如果您对如何实现更清晰、更易于阅读的解决方案有任何想法,请分享。

最佳答案

如果您不想使用任何Gem,那么......

试试这个(这将转换为百万):

def in_words(int)
numbers_to_name = {
1000000 => "million",
1000 => "thousand",
100 => "hundred",
90 => "ninety",
80 => "eighty",
70 => "seventy",
60 => "sixty",
50 => "fifty",
40 => "forty",
30 => "thirty",
20 => "twenty",
19=>"nineteen",
18=>"eighteen",
17=>"seventeen",
16=>"sixteen",
15=>"fifteen",
14=>"fourteen",
13=>"thirteen",
12=>"twelve",
11 => "eleven",
10 => "ten",
9 => "nine",
8 => "eight",
7 => "seven",
6 => "six",
5 => "five",
4 => "four",
3 => "three",
2 => "two",
1 => "one"
}
str = ""
numbers_to_name.each do |num, name|
if int == 0
return str
elsif int.to_s.length == 1 && int/num > 0
return str + "#{name}"
elsif int < 100 && int/num > 0
return str + "#{name}" if int%num == 0
return str + "#{name} " + in_words(int%num)
elsif int/num > 0
return str + in_words(int/num) + " #{name} " + in_words(int%num)
end
end
end



puts in_words(4) == "four"
puts in_words(27) == "twenty seven"
puts in_words(102) == "one hundred two"
puts in_words(38_079) == "thirty eight thousand seventy nine"
puts in_words(82102713) == "eighty two million one hundred two thousand seven hundred thirteen"

关于ruby-on-rails - 在 ruby​​ on Rails 中将数字转换为单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30030764/

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