Automatic Unit Conversion Function

Hi

Is it possible in Unitful.jl or DynamicQuantities.jl given a set of preferred units e.g. [u"ms",u"mm",u"mJ",u"g"] to have a function that can convert any given value e.g. 10u"W" to the correct units. I have tried upreferred but it seems not to always work, in the case of converting the Boltzmann constant from J/K to eV/K it seemed not to want to because it fell back on a default. The code I was using appeared something like the following.

function __init__()
    Unitful.preferunits(u"ms",u"mm",u"mJ",u"g")
end

function convert_units(value)
    if value isa Quantity || first(value) isa Quantity
        val = upreferred.(value)
        return Float64.(ustrip(val))
    else
        return value
    end
end

Any assistance would be fantastic

Thank you

1 Like