Unitful.jl
Unitful.jl copied to clipboard
Can't `convert(Float64, unitful_float64)`?
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?
convert is called automatically in many places, it would break the safety of putting units on values if they could be automatically stripped anywhere!
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.