Permalink
Browse files

Use the correct Numeric types

* to_d casts to BigDecimal, and is used everywhere
* to_f casts to Float
* to_i casts to Fixnum

Apparently Kernel#Float and Kernel#Integer check the
class of the result after calling to_f/to_i on it. Lame.
  • Loading branch information...
1 parent ee8f8b8 commit 89f4c980fc0b2176bfc55d948400a5bc092850d5 @foca foca committed Feb 1, 2010
Showing with 17 additions and 7 deletions.
  1. +9 −5 lib/scrooge.rb
  2. +8 −2 spec/scrooge_spec.rb
View
@@ -20,11 +20,15 @@ def initialize(cents)
end
def to_i
- to_f.to_i
+ to_d.to_i
end
def to_f
- Float(to_cents.to_s) / 100.0
+ to_d.to_f
+ end
+
+ def to_d
+ BigDecimal(to_cents.to_s) / BigDecimal("100")
end
def to_money
@@ -68,15 +72,15 @@ def coerce(other)
end
def method_missing(method, *args, &block)
- to_f.send(method, *args, &block)
+ to_d.send(method, *args, &block)
end
def respond_to?(method, include_private=false)
- to_f.respond_to?(method, include_private)
+ to_d.respond_to?(method, include_private)
end
def to_s
- sprintf("%.2f", to_f)
+ sprintf("%.2f", to_d)
end
end
end
View
@@ -6,15 +6,21 @@
describe Money do
subject { Money.new(175) }
- it "can be interpreted as an integer" do
+ it "can be interpreted as an Integer" do
subject.to_i.should == 1
+ subject.to_i.class.should == Fixnum
end
- it "can be interpreted as a float" do
+ it "can be interpreted as a Float" do
subject.to_f.should == 1.75
subject.to_f.class.should == Float
end
+ it "can be interpreted as a BigDecimal" do
+ subject.to_d.should == 1.75
+ subject.to_d.class.should == BigDecimal
+ end
+
it "can be zero" do
subject.should_not be_zero
Money.new(0).should be_zero

0 comments on commit 89f4c98

Please sign in to comment.