Ruby-on-rails 数字到英文单词转换 Rails
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3966159/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Number to English Word Conversion Rails
提问by Palani Kannan
Anybody knows the method to convert the numericals to english number words in rails?
有人知道在rails中将数字转换为英文数字单词的方法吗?
I found some Ruby scripts to convert numbericals to english words for corresponding words.
我找到了一些 Ruby 脚本来将数字转换为对应单词的英文单词。
Instead of writing a script in ruby, i feel that direct function is available.
不是用ruby写脚本,我觉得直接函数是可用的。
Eg. 1 -> One, 2 -> Two.
例如。1 -> 一,2 -> 二。
采纳答案by Mischa
No, you have to write a function yourself. The closest thing to what you want is number_to_human, but that does not convert 1to One.
不,你必须自己写一个函数。与您想要的最接近的是number_to_human,但这不会转换1为One.
Here are some URLs that may be helpful:
以下是一些可能有用的 URL:
回答by dB.
回答by Geoffroy
There is still the humanize gemthat does exactly what you want...
仍然有人性化的宝石可以完全满足您的需求......
require 'humanize'
23.humanize # => "twenty three"
0.42.humanize(decimals_as: :digits) # => "zero point four two"
回答by taimur akhtar
回答by jayant
How about this? Written for converting numbers to words in the Indian system, but can be easily modified.
这个怎么样?用于在印度系统中将数字转换为单词,但可以轻松修改。
def to_words(num)
numbers_to_name = {
10000000 => "crore",
100000 => "lakh",
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"
}
log_floors_to_ten_powers = {
0 => 1,
1 => 10,
2 => 100,
3 => 1000,
4 => 1000,
5 => 100000,
6 => 100000,
7 => 10000000
}
num = num.to_i
return '' if num <= 0 or num >= 100000000
log_floor = Math.log(num, 10).floor
ten_power = log_floors_to_ten_powers[log_floor]
if num <= 20
numbers_to_name[num]
elsif log_floor == 1
rem = num % 10
[ numbers_to_name[num - rem], to_words(rem) ].join(' ')
else
[ to_words(num / ten_power), numbers_to_name[ten_power], to_words(num % ten_power) ].join(' ')
end
end
回答by Satish
You may also want to check gem 'rupees' - https://github.com/railsfactory-shiv/rupeesto convert numbers to indian rupees (e.g. in Lakh, Crore, etc)
您可能还想检查 gem 'rupees' - https://github.com/railsfactory-shiv/rupees将数字转换为印度卢比(例如,十万、克罗等)

![Ruby-on-rails Rails 4 [最佳实践] 嵌套资源和浅层:true](/res/img/loading.gif)