Skip to content

Commit

Permalink
Support Float32/Float16 etc. type conversions (PainterQubits#296)
Browse files Browse the repository at this point in the history
  • Loading branch information
cstjean authored and ajkeller34 committed Jan 16, 2020
1 parent 80dfe91 commit b3d7357
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
18 changes: 11 additions & 7 deletions src/quantities.jl
Original file line number Diff line number Diff line change
Expand Up @@ -383,13 +383,17 @@ function frexp(x::AbstractQuantity{T}) where {T <: AbstractFloat}
a*unit(x), b
end

"""
float(x::AbstractQuantity)
Convert the numeric backing type of `x` to a floating-point representation.
Returns a `Quantity` with the same units.
"""
float(x::AbstractQuantity) = Quantity(float(x.val), unit(x))

for f in (:float, :BigFloat, :Float64, :Float32, :Float16)
@eval begin
"""
$($f)(x::AbstractQuantity)
Convert the numeric backing type of `x` to a floating-point representation.
Returns a `Quantity` with the same units.
"""
(Base.$f)(x::AbstractQuantity) = Quantity($f(x.val), unit(x))
end
end

"""
Integer(x::AbstractQuantity)
Convert the numeric backing type of `x` to an integer representation.
Expand Down
1 change: 1 addition & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,7 @@ end
@testset "> Unitful ↔ unitful conversion" begin
@testset ">> Numeric conversion" begin
@test @inferred(float(3m)) === 3.0m
@test @inferred(Float32(3m)) === 3.0f0m
@test @inferred(Integer(3.0A)) === 3A
@test Rational(3.0m) === (Int64(3)//1)*m
@test typeof(convert(typeof(0.0°), 90°)) == typeof(0.0°)
Expand Down

0 comments on commit b3d7357

Please sign in to comment.