Unitful - derived unit simplification?

I am fairly new to Unitful and am running into an issue when I multiply a derived unit by one of its component units and want the resulting unit to simplify into the other component unit.

Example:

> 1u"M" * 1u"L"
1 L M  # This should equal "1 mol"

> 1u"mol/L" * 1u"L"
1 mol  # The desired behavior works with base units.
> typeof(1u"M")
Quantity{Int64, 𝐍 𝐋⁻³, Unitful.FreeUnits{(M,), 𝐍 𝐋⁻³, nothing}}

> typeof(1u"L")
Quantity{Int64, 𝐋³, Unitful.FreeUnits{(L,), 𝐋³, nothing}}

Is there an easy way to fix this instead of resorting to only using base units?

Edit: I run into the same issue when multiplying liters and cm3, where they should cancel out.

> 1u"L" * 1u"1/cm^3"
1 L cm⁻³
1 Like

if you know what unit you expect, you can use uconvert or call the units as functions:

julia> uconvert(u"mol", 1u"M" * 1u"L")
1 mol

julia> uconvert(NoUnits, 1u"L" * 1u"1/cm^3")
1000

julia> 1u"M" * 1u"L" |> u"mol"
1 mol

julia> 1u"L" * 1u"1/cm^3" |> NoUnits
1000

if you don’t know the dimension, you can use upreferred, which by default shows SI units (this is configurable with preferunits)

julia> upreferred(3u"J/kg")
3 m^2 s^-2

see the relevant documentation for more: Conversion/promotion Β· Unitful.jl

6 Likes

Thank you! upreferred simplifies the units perfectly.

Now my examples become:

julia> 1u"M" * 1u"L" |> upreferred
1 mol

julia> 1u"L" * 1u"1/cm^3" |> upreferred
1000

A related post recently came up with the same issue: Make Unitful simplify expressions like 1ΞΌm/1m to a unitless value by default