Created
February 22, 2012 13:23
-
-
Save nerf/1885163 to your computer and use it in GitHub Desktop.
Convert numbers to Bulgarian words - list of numbers is incomplete (and It's not intended to be complete)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Example | |
# in template: <%= number_to_bg_words something.price, :format => '%i и %f' %> | |
# result: триста и дванадесет лева и петдесет и шест стотинки | |
######################## | |
# encoding: UTF-8 | |
module DocumentHelper | |
@@number_to_word = { | |
'1' => 'един', | |
'2' => 'два', | |
'3' => 'три', | |
'4' => 'четири', | |
'5' => 'пет', | |
'6' => 'шест', | |
'7' => 'седем', | |
'8' => 'осем', | |
'9' => 'девет', | |
'10' => 'десет', | |
'11' => 'единадесет', | |
'12' => 'дванадесет', | |
'13' => 'тринадесет', | |
'14' => 'четиринадесет', | |
'15' => 'петнадесет', | |
'16' => 'шестнадесет', | |
'17' => 'седемнадесет', | |
'18' => 'осемнадесет', | |
'19' => 'деветнадесет', | |
'20' => 'двадесет', | |
'30' => 'тридесет', | |
'40' => 'четиридесет', | |
'50' => 'петдесет', | |
'60' => 'шейсет', | |
'70' => 'седемдесет', | |
'80' => 'осемдесет', | |
'90' => 'деветдесет', | |
'100' => 'сто', | |
'200' => 'двеста', | |
'300' => 'триста', | |
'400' => 'четиристотин', | |
'500' => 'петстотин', | |
'600' => 'шестстотин', | |
'700' => 'седемстотин', | |
'800' => 'осемстотин', | |
'900' => 'деветстотин', | |
'1000' => 'хиляда', | |
'2000' => 'две хиляди', | |
'3000' => 'три хиляди', | |
} | |
def number_to_bg_words(number) | |
integer_words = [] | |
fractional_words = [] | |
num_s = number.to_s | |
if number.kind_of? Float | |
int = num_s.gsub /\.\d+/, '' | |
fra = num_s.gsub /^\d+\./, '' | |
# before decimal point | |
find_word(int, integer_words) | |
# after | |
if fra.to_i > 0 | |
find_word(fra, fractional_words) | |
end | |
elsif number.kind_of? Fixnum | |
find_word(num_s, integer_words) | |
else | |
return | |
end | |
output = String::new | |
unless integer_words.empty? | |
output << "#{integer_words.join(' и ')} лева" | |
end | |
unless fractional_words.empty? | |
output << " и #{fractional_words.join(' и ')} стотинки" | |
end | |
output.html_safe | |
end | |
private | |
def find_word (num_str, words_list) | |
num_length = num_str.length | |
num_length.times do |i| | |
if @@number_to_word[num_str[i,num_length]].nil? == false | |
words_list.push @@number_to_word[num_str[i,num_length]] | |
break | |
else | |
round = num_str[i] | |
(num_length - (i + 1)).times { round << 0.to_s } | |
if @@number_to_word[round].nil? == false | |
words_list.push @@number_to_word[round] | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment