Skip to content

Instantly share code, notes, and snippets.

@cmhobbs
Created November 12, 2010 15:35
Show Gist options
  • Save cmhobbs/674227 to your computer and use it in GitHub Desktop.
Save cmhobbs/674227 to your computer and use it in GitHub Desktop.
duck punchin' #to_cents method and some tests
class String
def to_cents
regex = /[\,$]/
if self.match(regex)
self.gsub!(regex, "")
end
if self.match(/\./)
dollars, change = self.split(".")
(dollars + change).to_i
else
self.to_i * 100
end
end
end
class Float
def to_cents
self.to_i * 100
end
end
class Fixnum
def to_cents
self * 100
end
end
require './cents.rb'
describe String do
describe "to_cents" do
it "should convert currency in strings with commas into cents properly" do
"1,000".to_cents.should == 100000
end
it "should convert currency strings with commas and decimals properly" do
"1,000.00".to_cents.should == 100000
end
it "should convert currency strings properly" do
"1000".to_cents.should == 100000
end
it "should convert currency strings with change properly" do
"1000.23".to_cents.should == 100023
end
it "should convert currency strings with commas and change properly" do
"1,100.23".to_cents.should == 110023
end
it "should convert currency strings with commas decimals and dolla signs properly" do
"$1,100.23".to_cents.should == 110023
end
end
end
describe Float do
describe "to_cents" do
it "should convert whole values with change properly" do
1000.00.to_cents.should == 100000
end
end
end
describe Fixnum do
describe "to_cents" do
it "should convert whole values without change properly" do
1000.to_cents.should == 100000
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment