module Bizsh::ToNum

Take string-ish numbers, like dollar amounts numbers with commas, and convert into a ruby number.

Public Instance Methods

to_num() click to toggle source
# File lib/bizsh.rb, line 57
def to_num
  # TODO - Make this work for folks that don't use ",'s" in their numbers.
  if match = self.match(/^\s*\$?\s*([\d\,]+)\.?(\d+)?\s*$/)
    whole, decimal = match.captures
    # Remove non-numeral out of the string.
    whole.gsub!(/[^\d]/, '')
    # Now cast it depending on if its a decimal value, or not.
    if whole && decimal
      [whole, '.', decimal].join.to_f
    elsif whole && !decimal
      whole.to_i
    end
  else
    0 # or should we just blow up?
  end
end