Module: Quickbooks::Support::Amount

Defined in:
lib/quickbooks/ruby_ext.rb

Class Method Summary collapse

Class Method Details

.new(whatever) ⇒ Object



162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/quickbooks/ruby_ext.rb', line 162

def self.new(whatever)
  amt = case
  when whatever.is_a?(String)
    # Sanitize the string, taking out things like $.
    whatever.gsub(/[^\d\.+-]/,'').match(/([+-]?\d{1,13}(?:\.\d\d)?)/)[1]
  when whatever.respond_to?(:to_f)
    whatever # cool, it can do to_f
  when whatever.respond_to?(:to_s)
    self.new(whatever.to_s) # to_s will be the second-best opportunity
  when whatever.respond_to?(:to_i)
    whatever.to_i # last resort, use integer
  else
    raise "Invalid value for Amount. Must be up to 13 digits with optional 2-digit decimal place."
  end
  # Format it
  "%.2f" % amt.to_f
end