Unit conversion

Hi,

I am new to Julia and am trying out Unitful. I would like to do the following:

a = 1"m" / 1"cm"

and have it return 100.

What must I do to make this happen? It is clearly not automatic. Similarly, I would like:

b = 1"in"

to return 0.003937 * u"m"

In other words, I would like an automatic convert to SI units.

Thanks,

Gordon

Try upreferred() IIRC

1 Like

I think automatic conversion is not recommended and so the Unitful devs opted for not doing it. For SI units conversion, I think upreferred generally does the trick:

julia> a = 1u"m" / 1u"cm"
1.0 m cm^-1

julia> upreferred(a)
100.0

julia> b = 1.0u"inch"
1.0 inch

julia> upreferred(b)
0.0254 m

But I think being explicit with your conversion is probably a better idea, and the pipe operator offers nice syntax for this IMHO:

julia> a |> unit(1) # maybe there is a better unitless unit
100.0

julia> b |> u"m"
0.0254 m
4 Likes
julia> uconvert(NoUnits,1u"m"/1u"cm")
100.0
julia> uconvert(u"m",1.0u"inch")
0.0254 m
4 Likes

Thank you very much for your replies. Yes, I concluded the same, but was wondering whether I had missed some capability. I appreciate the quick response!

This also works:

julia> 1u"m"/1u"cm" |> u"m/m"
100.0

which feels like an assertion that it’s a ratio of lengths, but it’s actually only asserting that it is unitless. Note that this works as well:

julia> 1u"m"/1u"cm" |> u"V/V"
100.0

Thanks. Is there a method to convert any unit into SI units? So far, all I seen is how to convert from one unit to another, but I have to specify the target units.

upreferred? Is there any case where it doesn’t convert to SI?

I think the problem is that saying “convert to SI” isn’t specific enough. Do you want Newtons? Or kg*m/s^2? I think that’s why you have to specify.

Excellent point. Thanks.

By the way, there is SI units with lengths in meters, and SI units with lengths in millimeters. Both are in common use.

Thanks. I really thought meters was some kind of default. I come from the Brian environment in Python, and I just got used to it.

Gordon

It’s easy to convert to base SI units without ambiguity. The base units are m, s, kg, K, A, mol, cd. The odd one out is kg, the others are without prefix.

Normalizing should be straightforward.