Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't convert(Float64, unitful_float64)? #742

Open
asinghvi17 opened this issue Oct 11, 2024 · 2 comments
Open

Can't convert(Float64, unitful_float64)? #742

asinghvi17 opened this issue Oct 11, 2024 · 2 comments

Comments

@asinghvi17
Copy link
Contributor

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?

@rafaqz
Copy link
Contributor

rafaqz commented Oct 12, 2024

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

@brainandforce
Copy link

brainandforce commented Oct 17, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants