# Automatic Unit Conversion Function

**URL:** <https://discourse.julialang.org/t/automatic-unit-conversion-function/128121>\
**Category:** Numerics\
**Tags:** unitful\
**Created:** [April 16, 2025, 10:57am UTC](https://discourse.julialang.org/t/automatic-unit-conversion-function/128121 "2025-04-16T10:57:33Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![HSnowden](https://avatars.discourse-cdn.com/v4/letter/h/58f4c7/32.png) [@HSnowden](https://discourse.julialang.org/u/HSnowden)\
**Post date:** [April 16, 2025, 10:57am UTC](https://discourse.julialang.org/t/automatic-unit-conversion-function/128121/1 "2025-04-16T10:57:33Z")

</div>

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.

```julia
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
