Skip to content

Commit

Permalink
Merge pull request #249 from rafaqz/round
Browse files Browse the repository at this point in the history
add two arg rounding methods
  • Loading branch information
ajkeller34 committed Jun 27, 2019
2 parents 1304c08 + b24d9fb commit 4508c86
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
13 changes: 9 additions & 4 deletions src/quantities.jl
Original file line number Diff line number Diff line change
Expand Up @@ -276,11 +276,16 @@ _dimerr(f) = error("$f can only be well-defined for dimensionless ",
"different results.")
isinteger(x::AbstractQuantity) = _dimerr(isinteger)
isinteger(x::DimensionlessQuantity) = isinteger(uconvert(NoUnits, x))

_rounderr(f) = error("Specify the type of the quantity to convert to with $f. ",
"Example: $f(typeof(1u\"m\"), 137u\"cm\") ")

for f in (:floor, :ceil, :trunc, :round)
@eval ($f)(x::AbstractQuantity; digits=0) = _dimerr($f)
@eval ($f)(x::DimensionlessQuantity; digits=0) = ($f)(uconvert(NoUnits, x); digits=digits)
@eval ($f)(::Type{T}, x::AbstractQuantity) where {T <: Integer} = _dimerr($f)
@eval ($f)(::Type{T}, x::DimensionlessQuantity) where {T <: Integer} = ($f)(T, uconvert(NoUnits, x))
@eval ($f)(x::AbstractQuantity; kwargs...) = _rounderr($f)
@eval ($f)(x::DimensionlessQuantity; kwargs...) = ($f)(uconvert(NoUnits, x); kwargs...)
@eval ($f)(::Type{T}, x::AbstractQuantity; kwargs...) where {T <: Integer} = _rounderr($f)
@eval ($f)(::Type{T}, x::DimensionlessQuantity; kwargs...) where {T <: Integer} = ($f)(T, uconvert(NoUnits, x); kwargs...)
@eval ($f)(::Type{T}, x::Quantity; kwargs...) where {T <: Quantity} = T(($f)(uconvert(unit(T), x).val; kwargs...))
end

zero(x::AbstractQuantity) = Quantity(zero(x.val), unit(x))
Expand Down
12 changes: 12 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -888,6 +888,18 @@ end
@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)
@test floor(typeof(1mm), 1.0314m) === 1031mm
@test floor(typeof(1.0mm), 1.0314m) === 1031.0mm
@test floor(typeof(1.0mm), 1.0314m; digits=1) === 1031.4mm
@test ceil(typeof(1mm), 1.0314m) === 1032mm
@test ceil(typeof(1.0mm), 1.0314m) === 1032.0mm
@test ceil(typeof(1.0mm), 1.0314m; digits=1) === 1031.4mm
@test trunc(typeof(1mm), -1.0314m) === -1031mm
@test trunc(typeof(1.0mm), -1.0314m) === -1031.0mm
@test trunc(typeof(1.0mm), -1.0314m; digits=1) === -1031.4mm
@test round(typeof(1mm), 1.0314m) === 1031mm
@test round(typeof(1.0mm), 1.0314m) === 1031.0mm
@test round(typeof(1.0mm), 1.0314m; digits=1) === 1031.4mm
end

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

0 comments on commit 4508c86

Please sign in to comment.