summaryrefslogtreecommitdiff
path: root/ext/bigdecimal/lib/bigdecimal/util.rb
blob: 1f8d6c7a49c07dade96661c1f00192db86683d86 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#
# BigDecimal utility library.
# ----------------------------------------------------------------------
# Contents:
#
#   String#
#     to_d      ... to BigDecimal
#
#   Float#
#     to_d      ... to BigDecimal
#
#   BigDecimal#
#     to_r      ... to Rational
#
#   Rational#
#     to_d      ... to BigDecimal
#
# ----------------------------------------------------------------------
#
class Float < Numeric
  def to_d
    BigDecimal(self.to_s)
  end
end

class String
  def to_d
    BigDecimal(self)
  end
end

class BigDecimal < Numeric
  # to "nnnnnn.mmm" form digit string
  # Use BigDecimal#to_s("F") instead.
  def to_digits
     if self.nan? || self.infinite? || self.zero?
        self.to_s
     else
       i       = self.to_i.to_s
       s,f,y,z = self.frac.split
       i + "." + ("0"*(-z)) + 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
  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