views:

233

answers:

2

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).

+4  A: 

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
+1 Was just writing EXACTLY the same code when you answer came up
DanSingerman
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
@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
+1  A: 

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