0

I try to convert number to words but I have a problem:

>> (91.80).en.numwords
=> "ninety-one point eight"

I want it to be "ninety-one point eighty". I use Linguistics gem. Do you know some solution for it (prefer with Linguistics).

Jonas Elfström
  • 30,834
  • 6
  • 70
  • 106
Sebastian
  • 2,618
  • 3
  • 25
  • 32

3 Answers3

4

It's a bit hackish, but it works:

'91.80'.split('.').map {|i| i.en.numwords}.join(' point ')
=> "ninety-one point eighty"

When you put 91.80 as a float, ruby gets rid of the trailing zero, so it needs to be a string to begin with to retain that information. A better example might have been:

'91.83'.split('.').map {|i| i.en.numwords}.join(' point ')
 => "ninety-one point eighty-three"
ealdent
  • 3,677
  • 1
  • 25
  • 26
  • +1 Was just writing EXACTLY the same code when you answer came up – DanSingerman Dec 18 '09 at 13:23
  • IMO what you wrote is not correct answer. number = 91.80 number.split('.').map {|i| i.en.numwords}.join(' point ') => "ninety-one point eight" – Sebastian Dec 18 '09 at 14:11
  • @Sebastian, you have to start with the number represented as a string, otherwise there's no actual difference in memory between how 91.8 and 91.80 are stored. (You literally can't tell them apart.) – Ken Bloom Dec 18 '09 at 17:14
1

If you use the Linguistics gem with Ruby 1.9 you'll need to patch line 1060 of en.rb

# Ruby 1.8 -->  fn = NumberToWordsFunctions[ digits.nitems ]
# Ruby 1.9 removed Array.nitems so we get -->  fn = NumberToWordsFunctions[ digits.count{|x| !x.nil?} ]
fn = NumberToWordsFunctions[ digits.count{|x| !x.nil?} ]

We submitted the small patch to the author.

Chris
  • 11
  • 1
0

I got answer by myself.

def amount_to_words(number)
  unless (number % 1).zero?
    number = number.abs if number < 0
    div = number.div(1)                      
    mod = (number.modulo(1) * 100).round    
    [div.to_s.en.numwords, "point", mod.to_s.en.numwords].join(" ")
  else
    number.en.numwords
  end
end

And result:

>> amount_to_words(-91.83)
=> "ninety-one point eighty-three"
>> amount_to_words(-91.8)
=> "ninety-one point eighty"
>> amount_to_words(91.8)
=> "ninety-one point eighty"
>> amount_to_words(91.83)
=> "ninety-one point eighty-three"

Although, thank you guys. Your idea with to_s was helpful for me.

Sebastian
  • 2,618
  • 3
  • 25
  • 32