~ubuntu-branches/ubuntu/hardy/ruby1.8/hardy-updates

« back to all changes in this revision

Viewing changes to ext/bigdecimal/lib/bigdecimal/util.rb

  • Committer: Bazaar Package Importer
  • Author(s): akira yamada
  • Date: 2007-03-13 22:11:58 UTC
  • mfrom: (1.1.5 upstream)
  • Revision ID: james.westby@ubuntu.com-20070313221158-h3oql37brlaf2go2
Tags: 1.8.6-1
* new upstream version, 1.8.6.
* libruby1.8 conflicts with libopenssl-ruby1.8 (< 1.8.6) (closes: #410018)
* changed packaging style to cdbs from dbs.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#
 
2
# BigDecimal utility library.
 
3
#
 
4
# To use these functions, require 'bigdecimal/util'
 
5
#
 
6
# The following methods are provided to convert other types to BigDecimals:
 
7
#
 
8
#   String#to_d -> BigDecimal
 
9
#   Float#to_d -> BigDecimal
 
10
#   Rational#to_d -> BigDecimal
 
11
#
 
12
# The following method is provided to convert BigDecimals to other types:
 
13
#
 
14
#   BigDecimal#to_r -> Rational
 
15
#
 
16
# ----------------------------------------------------------------------
 
17
#
 
18
class Float < Numeric
 
19
  def to_d
 
20
    BigDecimal(self.to_s)
 
21
  end
 
22
end
 
23
 
 
24
class String
 
25
  def to_d
 
26
    BigDecimal(self)
 
27
  end
 
28
end
 
29
 
 
30
class BigDecimal < Numeric
 
31
  # Converts a BigDecimal to a String of the form "nnnnnn.mmm".
 
32
  # This method is deprecated; use BigDecimal#to_s("F") instead.
 
33
  def to_digits
 
34
     if self.nan? || self.infinite? || self.zero?
 
35
        self.to_s
 
36
     else
 
37
       i       = self.to_i.to_s
 
38
       s,f,y,z = self.frac.split
 
39
       i + "." + ("0"*(-z)) + f
 
40
     end
 
41
  end
 
42
 
 
43
  # Converts a BigDecimal to a Rational.
 
44
  def to_r 
 
45
     sign,digits,base,power = self.split
 
46
     numerator = sign*digits.to_i
 
47
     denomi_power = power - digits.size # base is always 10
 
48
     if denomi_power < 0
 
49
        Rational(numerator,base ** (-denomi_power))
 
50
     else
 
51
        Rational(numerator * (base ** denomi_power),1)
 
52
     end
 
53
  end
 
54
end
 
55
 
 
56
class Rational < Numeric
 
57
  # Converts a Rational to a BigDecimal
 
58
  def to_d(nFig=0)
 
59
     num = self.numerator.to_s
 
60
     if nFig<=0
 
61
        nFig = BigDecimal.double_fig*2+1
 
62
     end
 
63
     BigDecimal.new(num).div(self.denominator,nFig)
 
64
  end
 
65
end