summaryrefslogtreecommitdiff
path: root/ext/bigdecimal/lib/bigdecimal
diff options
context:
space:
mode:
authorKenta Murata <mrkn@mrkn.jp>2019-10-09 10:39:39 +0900
committerNobuyoshi Nakada <nobu@ruby-lang.org>2020-07-06 01:15:46 +0900
commit03a33603c66bf6eca6937d221f87daf3f5a489f7 (patch)
tree5edac3f58fed2349428a37d12d23aee34954658a /ext/bigdecimal/lib/bigdecimal
parent6607212224401d852c0056b841be7ff95236e8f7 (diff)
[ruby/bigdecimal] Add Complex#to_d
https://github.com/ruby/bigdecimal/commit/97e794ac97
Notes
Notes: Merged: https://github.com/ruby/ruby/pull/3295
Diffstat (limited to 'ext/bigdecimal/lib/bigdecimal')
-rw-r--r--ext/bigdecimal/lib/bigdecimal/util.rb33
1 files changed, 33 insertions, 0 deletions
diff --git a/ext/bigdecimal/lib/bigdecimal/util.rb b/ext/bigdecimal/lib/bigdecimal/util.rb
index 4ece8347bd..66fff7867b 100644
--- a/ext/bigdecimal/lib/bigdecimal/util.rb
+++ b/ext/bigdecimal/lib/bigdecimal/util.rb
@@ -131,6 +131,39 @@ class Rational < Numeric
end
+class Complex < Numeric
+ # call-seq:
+ # cmp.to_d -> bigdecimal
+ # cmp.to_d(precision) -> bigdecimal
+ #
+ # Returns the value as a BigDecimal.
+ #
+ # The +precision+ parameter is required for a rational complex number.
+ # This parameter is used to determine the number of significant digits
+ # for the result.
+ #
+ # require 'bigdecimal'
+ # require 'bigdecimal/util'
+ #
+ # Complex(0.1234567, 0).to_d(4) # => 0.1235e0
+ # Complex(Rational(22, 7), 0).to_d(3) # => 0.314e1
+ #
+ # See also BigDecimal::new.
+ #
+ def to_d(*args)
+ BigDecimal(self) unless self.imag.zero? # to raise eerror
+
+ if args.length == 0
+ case self.real
+ when Rational
+ BigDecimal(self.real) # to raise error
+ end
+ end
+ self.real.to_d(*args)
+ end
+end
+
+
class NilClass
# call-seq:
# nil.to_d -> bigdecimal