~ubuntu-branches/ubuntu/intrepid/ruby1.9/intrepid-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-05-21 14:00:19 UTC
  • mfrom: (1.1.4 upstream)
  • Revision ID: james.westby@ubuntu.com-20070521140019-ui4zd0v80duktssk
Tags: 1.9.0+20070521-1
new upstream snapshot. (2006-07-21)  (Closes: #414856, #388344)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
#
2
2
# BigDecimal utility library.
3
 
# ----------------------------------------------------------------------
4
 
# Contents:
5
 
#
6
 
#   String#
7
 
#     to_d      ... to BigDecimal
8
 
#
9
 
#   Float#
10
 
#     to_d      ... to BigDecimal
11
 
#
12
 
#   BigDecimal#
13
 
#     to_r      ... to Rational
14
 
#
15
 
#   Rational#
16
 
#     to_d      ... to BigDecimal
 
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
17
15
#
18
16
# ----------------------------------------------------------------------
19
17
#
30
28
end
31
29
 
32
30
class BigDecimal < Numeric
33
 
  # to "nnnnnn.mmm" form digit string
34
 
  # Use BigDecimal#to_s("F") instead.
 
31
  # Converts a BigDecimal to a String of the form "nnnnnn.mmm".
 
32
  # This method is deprecated; use BigDecimal#to_s("F") instead.
35
33
  def to_digits
36
34
     if self.nan? || self.infinite? || self.zero?
37
35
        self.to_s
42
40
     end
43
41
  end
44
42
 
45
 
  # Convert BigDecimal to Rational
 
43
  # Converts a BigDecimal to a Rational.
46
44
  def to_r 
47
45
     sign,digits,base,power = self.split
48
46
     numerator = sign*digits.to_i
49
47
     denomi_power = power - digits.size # base is always 10
50
48
     if denomi_power < 0
51
 
        denominator = base ** (-denomi_power)
 
49
        Rational(numerator,base ** (-denomi_power))
52
50
     else
53
 
        denominator = base ** denomi_power
 
51
        Rational(numerator * (base ** denomi_power),1)
54
52
     end
55
 
     Rational(numerator,denominator)
56
53
  end
57
54
end
58
55
 
59
56
class Rational < Numeric
60
 
  # Convert Rational to BigDecimal
 
57
  # Converts a Rational to a BigDecimal
61
58
  def to_d(nFig=0)
62
59
     num = self.numerator.to_s
63
60
     if nFig<=0