summaryrefslogtreecommitdiff
path: root/ext/bigdecimal/lib/bigdecimal-rational.rb
diff options
context:
space:
mode:
Diffstat (limited to 'ext/bigdecimal/lib/bigdecimal-rational.rb')
-rw-r--r--ext/bigdecimal/lib/bigdecimal-rational.rb30
1 files changed, 30 insertions, 0 deletions
diff --git a/ext/bigdecimal/lib/bigdecimal-rational.rb b/ext/bigdecimal/lib/bigdecimal-rational.rb
new file mode 100644
index 0000000000..de999d19cf
--- /dev/null
+++ b/ext/bigdecimal/lib/bigdecimal-rational.rb
@@ -0,0 +1,30 @@
+#
+# BigDecimal <-> Rational
+#
+class BigDecimal
+ # Convert BigDecimal to Rational
+ def to_r
+ sign,digits,base,power = self.to_parts
+ numerator = sign*digits.to_i
+ denomi_power = power - digits.size # base is always 10
+ if denomi_power < 0
+ denominator = base ** (-denomi_power)
+ else
+ denominator = base ** denomi_power
+ end
+ Rational.new(numerator,denominator)
+ end
+end
+
+class Rational
+ # Convert Rational to BigDecimal
+ # to_d returns an array [quotient,residue]
+ def to_d(nFig=0)
+ num = self.numerator.to_s
+ if nFig<=0
+ nFig = BigDecimal.double_fig*2+1
+ end
+ BigDecimal.new(num).div(self.denominator,nFig)
+ end
+end
+