Skip to content

Commit

Permalink
Add support for round(T, x) where T <: Integer (and friends)
Browse files Browse the repository at this point in the history
  • Loading branch information
mbauman committed Jun 8, 2017
1 parent ef27338 commit b9bc798
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
9 changes: 7 additions & 2 deletions src/Unitful.jl
Original file line number Diff line number Diff line change
Expand Up @@ -870,11 +870,16 @@ end
==(x::Number, y::Quantity) = ==(y,x)
<=(x::Quantity, y::Quantity) = <(x,y) || x==y

for f in (:floor, :ceil, :trunc, :round, :isinteger)
@eval ($f)(x::Quantity) = error("$($f) can only be well-defined for dimensionless ",
_dimerr(f) = error("$f can only be well-defined for dimensionless ",
"numbers. For dimensionful numbers, different input units yield physically ",
"different results.")
isinteger(x::Quantity) = _dimerr(isinteger)
isinteger(x::DimensionlessQuantity) = isinteger(uconvert(NoUnits, x))
for f in (:floor, :ceil, :trunc, :round)
@eval ($f)(x::Quantity) = _dimerr(f)
@eval ($f)(x::DimensionlessQuantity) = ($f)(uconvert(NoUnits, x))
@eval ($f){T<:Integer}(::Type{T}, x::Quantity) = _dimerr(f)
@eval ($f){T<:Integer}(::Type{T}, x::DimensionlessQuantity) = ($f)(T, uconvert(NoUnits, x))
end

zero(x::Quantity) = Quantity(zero(x.val), unit(x))
Expand Down
16 changes: 16 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -776,10 +776,26 @@ end
@test_throws ErrorException ceil(3.7m)
@test_throws ErrorException trunc(3.7m)
@test_throws ErrorException round(3.7m)
@test_throws ErrorException floor(Integer, 3.7m)
@test_throws ErrorException ceil(Integer, 3.7m)
@test_throws ErrorException trunc(Integer, 3.7m)
@test_throws ErrorException round(Integer, 3.7m)
@test_throws ErrorException floor(Int, 3.7m)
@test_throws ErrorException ceil(Int, 3.7m)
@test_throws ErrorException trunc(Int, 3.7m)
@test_throws ErrorException round(Int, 3.7m)
@test floor(1.0314m/mm) === 1031.0
@test ceil(1.0314m/mm) === 1032.0
@test trunc(-1.0314m/mm) === -1031.0
@test round(1.0314m/mm) === 1031.0
@test floor(Integer, 1.0314m/mm) === Integer(1031.0)
@test ceil(Integer, 1.0314m/mm) === Integer(1032.0)
@test trunc(Integer, -1.0314m/mm) === Integer(-1031.0)
@test round(Integer, 1.0314m/mm) === Integer(1031.0)
@test floor(Int16, 1.0314m/mm) === Int16(1031.0)
@test ceil(Int16, 1.0314m/mm) === Int16(1032.0)
@test trunc(Int16, -1.0314m/mm) === Int16(-1031.0)
@test round(Int16, 1.0314m/mm) === Int16(1031.0)
end

@testset "Sgn, abs, &c." begin
Expand Down

0 comments on commit b9bc798

Please sign in to comment.