Skip to content

Instantly share code, notes, and snippets.

@timuruski
Created March 6, 2009 06:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timuruski/74786 to your computer and use it in GitHub Desktop.
Save timuruski/74786 to your computer and use it in GitHub Desktop.
# Proof of concept
e = 2
c = 10**e
amt = 5.67
amt_i = (amt * c).to_i
amt_f = amt_i.to_f / c
tax = 11
tax_f = tax.to_f / 100
amt_tax = amt_f * tax_f
puts "sub-total: #{sprintf("$%.#{e}f", amt_f)}"
puts "tax: #{sprintf("$%.#{e}f", amt_tax)}"
puts "total: #{sprintf("$%.#{e}f", amt_f + amt_tax)}"
puts '--'
# Class implemtation
class Currency
def initialize(exp = 2, symbol = '$')
@exp = exp
@cent = 10**@exp
@symbol = symbol
end
def amount_to_i(float)
return (float * @cent).to_i
end
def amount_to_f(int)
return int.to_f / @cent
end
def amount_to_s(int)
"#{sprintf("#{@symbol}%.#{@exp}f", (int.to_f / @cent))}"
end
end
usd = Currency.new(2, '$')
puts i = usd.amount_to_i(2.4)
puts f = usd.amount_to_f(i)
puts s = usd.amount_to_s(i)
puts '--'
itl = Currency.new(3, '₤')
puts i = itl.amount_to_i(2.4)
puts f = itl.amount_to_f(i)
puts s = itl.amount_to_s(i)
puts '--'
jpy = Currency.new(0, '¥')
puts i = jpy.amount_to_i(2400)
puts f = jpy.amount_to_f(i)
puts s = jpy.amount_to_s(i)
puts '--'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment