summaryrefslogtreecommitdiff
path: root/ext/bigdecimal/lib/bigdecimal/util.rb
diff options
context:
space:
mode:
authorshigek <shigek@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2003-07-18 15:26:37 +0000
committershigek <shigek@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2003-07-18 15:26:37 +0000
commit1bb3071bde8344427a5fe3f5998dc491d2630d2b (patch)
tree8310d06d0fd319977dbc2b560d230c48f48f03da /ext/bigdecimal/lib/bigdecimal/util.rb
parente242cf9defb5442ef223535abe93399352cf139e (diff)
As discussed in ruby-dev ML:
lib directory moved. util.rb created instead of bigdecimal-rational.rb git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@4093 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'ext/bigdecimal/lib/bigdecimal/util.rb')
-rw-r--r--ext/bigdecimal/lib/bigdecimal/util.rb74
1 files changed, 74 insertions, 0 deletions
diff --git a/ext/bigdecimal/lib/bigdecimal/util.rb b/ext/bigdecimal/lib/bigdecimal/util.rb
new file mode 100644
index 0000000000..d9b7ae3131
--- /dev/null
+++ b/ext/bigdecimal/lib/bigdecimal/util.rb
@@ -0,0 +1,74 @@
+#
+# BigDecimal utility library.
+# ----------------------------------------------------------------------
+# Contents:
+#
+# String#
+# to_d ... to BigDecimal
+#
+# Float#
+# to_d ... to BigDecimal
+#
+# BigDecimal#
+# to_digits ... to xxxxx.yyyy form digit string(not 0.zzzE?? form).
+# to_r ... to Rational
+#
+# Rational#
+# to_d ... to BigDecimal
+#
+# ----------------------------------------------------------------------
+#
+class Float < Numeric
+ def to_d
+ BigFloat::new(selt.to_s)
+ end
+end
+
+class String
+ def to_d
+ BigDecimal::new(self)
+ end
+end
+
+class BigDecimal < Numeric
+ # to "nnnnnn.mmm" form digit string
+ def to_digits
+ if self.nan? || self.infinite?
+ self.to_s
+ else
+ s,i,y,z = self.fix.split
+ s,f,y,z = self.frac.split
+ if s > 0
+ s = ""
+ else
+ s = "-"
+ end
+ s + i + "." + f
+ end
+ end
+
+ # Convert BigDecimal to Rational
+ def to_r
+ sign,digits,base,power = self.split
+ 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(numerator,denominator)
+ end
+end
+
+class Rational < Numeric
+ # 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