OSDN Git Service

configured for android
[splhack/AndroidRuby.git] / lib / ruby-1.9.1-rc1 / .ext / common / bigdecimal / util.rb
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 end
43
44 class Rational < Numeric
45   # Converts a Rational to a BigDecimal
46   def to_d(nFig=0)
47      num = self.numerator.to_s
48      if nFig<=0
49         nFig = BigDecimal.double_fig*2+1
50      end
51      BigDecimal.new(num).div(self.denominator,nFig)
52   end
53 end