/tools/Ruby/lib/ruby/1.8/bigdecimal/util.rb

http://github.com/agross/netopenspace · Ruby · 65 lines · 40 code · 4 blank · 21 comment · 5 complexity · ab3d25a4e41505d534c3e5950d16219d MD5 · raw file

  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. class String
  24. def to_d
  25. BigDecimal(self)
  26. end
  27. end
  28. class BigDecimal < Numeric
  29. # Converts a BigDecimal to a String of the form "nnnnnn.mmm".
  30. # This method is deprecated; use BigDecimal#to_s("F") instead.
  31. def to_digits
  32. if self.nan? || self.infinite? || self.zero?
  33. self.to_s
  34. else
  35. i = self.to_i.to_s
  36. s,f,y,z = self.frac.split
  37. i + "." + ("0"*(-z)) + f
  38. end
  39. end
  40. # Converts a BigDecimal to a Rational.
  41. def to_r
  42. sign,digits,base,power = self.split
  43. numerator = sign*digits.to_i
  44. denomi_power = power - digits.size # base is always 10
  45. if denomi_power < 0
  46. Rational(numerator,base ** (-denomi_power))
  47. else
  48. Rational(numerator * (base ** denomi_power),1)
  49. end
  50. end
  51. end
  52. class Rational < Numeric
  53. # Converts a Rational to a BigDecimal
  54. def to_d(nFig=0)
  55. num = self.numerator.to_s
  56. if nFig<=0
  57. nFig = BigDecimal.double_fig*2+1
  58. end
  59. BigDecimal.new(num).div(self.denominator,nFig)
  60. end
  61. end