source: extensions/gsdl-video/trunk/installed/cmdline/lib/ruby/1.8/bigdecimal/util.rb@ 18425

Last change on this file since 18425 was 18425, checked in by davidb, 15 years ago

Video extension to Greenstone

File size: 1.5 KB
Line 
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#
18class Float < Numeric
19 def to_d
20 BigDecimal(self.to_s)
21 end
22end
23
24class String
25 def to_d
26 BigDecimal(self)
27 end
28end
29
30class 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
54end
55
56class 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
65end
Note: See TracBrowser for help on using the repository browser.