Unitful.jl icon indicating copy to clipboard operation
Unitful.jl copied to clipboard

Can't `convert(Float64, unitful_float64)`?

Open asinghvi17 opened this issue 1 year ago • 2 comments

MWE:

julia> using Unitful
julia> convert(Float64, 1.0u"m")
ERROR: DimensionError:  and m are not dimensionally compatible.
Stacktrace:
 [1] #s103#141
   @ ~/.julia/packages/Unitful/GYzMo/src/conversion.jl:7 [inlined]
 [2] var"#s103#141"(::Any, s::Any, t::Any)
   @ Unitful ./none:0
 [3] (::Core.GeneratedFunctionStub)(::UInt64, ::LineNumberNode, ::Any, ::Vararg{Any})
   @ Core ./boot.jl:602
 [4] uconvert(a::Unitful.FreeUnits{(), NoDims, nothing}, x::Quantity{Float64, 𝐋, Unitful.FreeUnits{(m,), 𝐋, nothing}})
   @ Unitful ~/.julia/packages/Unitful/GYzMo/src/conversion.jl:72
 [5] convert(::Type{Float64}, y::Quantity{Float64, 𝐋, Unitful.FreeUnits{(m,), 𝐋, nothing}})
   @ Unitful ~/.julia/packages/Unitful/GYzMo/src/conversion.jl:139
 [6] top-level scope
   @ REPL[274]:1

Looking into the code, it seems there is a special case to handle this. Did it bitrot at some point?

asinghvi17 avatar Oct 11 '24 22:10 asinghvi17

convert is called automatically in many places, it would break the safety of putting units on values if they could be automatically stripped anywhere!

rafaqz avatar Oct 12 '24 06:10 rafaqz

If you need to get the scalar value associated with a quantity, use ustrip(u::Units, x::Quantity), which converts x to the units u and then returns the scalar portion.

As @rafaqz mentioned above, ustrip(::Quantity) or other methods of generating a scalar are unsafe: 100u"m", 100u"km", and 100u"s" are all stripped to 100 even though they have totally different meanings.

brainandforce avatar Oct 17 '24 22:10 brainandforce