Skip to content

Commit

Permalink
Added #to_* conversion methods to Complex
Browse files Browse the repository at this point in the history
  • Loading branch information
Sija committed Aug 31, 2018
1 parent 8320859 commit 0ace999
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions src/complex.cr
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,48 @@ struct Complex < Number
false
end

# Returns `self`.
def to_c
self
end

# Returns the value as a `Float64` if possible (the imaginary part should be exactly zero),
# raises otherwise.
def to_f64
unless @imag.zero?
raise Exception.new "Complex number with non-zero imaginary part can't be converted to real number"
end
@real
end

# Returns the value as a `Float32` if possible (the imaginary part should be exactly zero),
# raises otherwise.
def to_f32
to_f64.to_f32
end

# See `#to_f64`.
def to_f
to_f64
end

# Returns the value as an `Int64` if possible (the imaginary part should be exactly zero),
# raises otherwise.
def to_i64
to_f64.to_i64
end

# Returns the value as a `Int32` if possible (the imaginary part should be exactly zero),
# raises otherwise.
def to_i32
to_i64.to_i32
end

# See `#to_i64`.
def to_i
to_i64
end

# Write this complex object to an *io*.
#
# ```
Expand Down

0 comments on commit 0ace999

Please sign in to comment.