Class: Abaco::Converter

Inherits:
Object
  • Object
show all
Defined in:
lib/abaco/converter.rb

Overview

Number converter

The convert converts numbers into Italian.

Author:

Defined Under Namespace

Classes: BigNumberError

Constant Summary collapse

EXCEPTIONS =
{
  'unocento'    => 'cento',
  'unomila'     => 'mille',
  'uno m'       => 'un m',
  /t\wmille/    => 'tunomila',
  'ntaotto'     => 'ntotto',
  'ntauno'      => 'ntuno',
  'un miliardi' => 'un miliardo',
  'un milioni'  => 'un milione',
  'ntoo'        => 'nto'
}
NUMBERS =
{
  units: ['', 'uno', 'due', 'tre', 'quattro', 'cinque', 'sei', 'sette', 'otto', 'nove'],
  teens: ['dieci', 'undici', 'dodici', 'tredici', 'quattordici', 'quindici', 'sedici', 'diciassette', 'diciotto', 'diciannove'],
  tens:  ['', 'dieci', 'venti', 'trenta', 'quaranta', 'cinquanta', 'sessanta', 'settanta', 'ottanta', 'novanta']
}
SUFFIXES =
{
  3 => 'mila',
  6 => 'milioni',
  9 => 'miliardi'
}
MAX_NUMBER =
999999999999

Class Method Summary collapse

Class Method Details

.convert(number) ⇒ String

Converts the given number into Italian words.

Parameters:

  • number (Numeric)

    the number to convert (<= 999.999.999.999)

Returns:

  • (String)

    A string in the ‘NUMBER/DD’ form, ‘DD’ being two decimal digits (these will be added even if the number is a Fixnum).

Raises:

  • BigNumberError if the number is too big to be converted



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/abaco/converter.rb', line 43

def self.convert(number)
  if number > MAX_NUMBER
    raise BigNumberError, "Abaco can't convert numbers bigger than #{MAX_NUMBER}"
  end

  number = number.to_f

  tmp = number.to_i
  result = ''

  9.step(3, -3) do |n|
    # Is the number in the 10^n form?
    if Math.log10(tmp).to_i >= n
      result += describe_part(tmp / 10 ** n)

      result += ' ' if n >= 6
      result += SUFFIXES[n]
      result += ' ' if n >= 6
    end

    tmp %= 10 ** n
  end

  decimal_part = '/'
  decimal_part += ('%.2f' % number).split('.').last

  result += describe_part(tmp) + decimal_part

  EXCEPTIONS.each_pair do |search, replace|
    result.gsub! search, replace
  end

  result
end