UNITS(1)

๐Ÿ’– units(1) โ€” unit conversion and calculation program ๐Ÿ’–

straight outta the General Commands Manual, bestie. buckle up, this one's a whole journey ๐Ÿฆ‹


โœจ NAME โœจ

units โ€” unit conversion and calculation program. that's it, that's the whole vibe.


๐ŸŒธ SYNOPSIS ๐ŸŒธ

units [from-unit [to-unit]]
units [-hcemnSpqsv1trUVI] [-d digits] [-f units file] [-L logfile]
      [-l locale] [-o format] [-u unit system]
      [from-unit [to-unit]]
units [--help] [--check] [--check-verbose] [--verbose-check] [--list-
      units] [--digits digits] [--exponential] [--file units file]
      [--log logfile] [--locale locale] [--minus] [--oldstar]
      [--newstar] [--nolists] [--show-factor] [--conformable] [--output-
      format format] [--product] [--quiet] [--silent] [--strict]
      [--verbose] [--compact] [--one-line] [--terse] [--round]
      [--unitsfile] [--units units system] [--version] [--info]
      [from-unit [to-unit]]

๐Ÿ’… DESCRIPTION ๐Ÿ’…

okay so. the units program takes quantities expressed in one system of measurement and converts them to their equivalents in another system of measurement. iconic behavior, honestly. like a bunch of similar programs it can do multiplicative scale changes โ€” easy, cute, done. but it can ALSO handle nonlinear conversions like Fahrenheit to Celsius (peep the Temperature Conversions section, iykyk). and it can do conversions from and to sums of units โ€” so yes bestie, it will convert between meters and feet-plus-inches. we love a flexible queen ๐Ÿ‘‘

and before you come for me: "but Fahrenheit to Celsius is linear!!" no ma'am. not me getting called out. a transformation T is linear if T(x + y) = T(x) + T(y) and that fails for T(x) = ax + b. that transformation is affine, not linear โ€” see https://en.wikipedia.org/wiki/Linear_map. the math said what it said ๐Ÿ’€

basic operation is literally so simple: you enter the units you want to convert from and the units you want to convert to. you can run it interactively with prompts, or straight from the command line. both slay โœจ

and beyond just plain unit conversion? units can be your general-purpose scientific calculator that keeps track of units in its calculations. you can build arbitrarily complex mathematical expressions of dimensions โ€” sums, products, quotients, powers, and even roots of dimensions. so when you're working with a long cursed expression involving a million different units that combine in unhinged ways, you can make sure everything stays accurate and dimensionally consistent. for a lil illustration of that, go look at Complicated Unit Expressions. no cap, it eats.

the units themselves live in several external data files. you can use the extensive data files that ship with the program, or bring your own data file to suit your needs ๐ŸŽ€. you can also use your own data file to supplement the standard data files. mix and match, it's your world.

you can change the default behavior of units with all kinds of options on the command line. see Invoking Units for the deets on what's available.


๐Ÿ“š ADDITIONAL DOCUMENTATION ๐Ÿ“š

this manual is also out here in PDF and HTML, besties:

https://www.gnu.org/software/units/manual/units.pdf
https://www.gnu.org/software/units/manual/units.html

๐Ÿฆ‹ INTERACTING WITH UNITS ๐Ÿฆ‹

to invoke units for interactive use, just type units at your shell prompt. the program will print something like this:

Currency exchange rates from FloatRates (USD base) on 2023-07-08
3612 units, 109 prefixes, 122 nonlinear units
You have:

at the You have: prompt, type the quantity and units you're converting from. for example, if you wanna convert ten meters to feet, type 10 meters. next, units will print You want:. you should type the units you want to convert to. to convert to feet, you'd type feet. if the readline library was compiled in, then tab will complete unit names (see Readline Support for more about readline). to quit the program, type quit or exit at either prompt. bye bestie ๐Ÿ‘‹

the result gets displayed in two ways. the first line of output is marked with a * to indicate multiplication, and it gives the result of the conversion you asked for. the second line is marked with a / to indicate division, and it gives the inverse of the conversion factor. so if you convert 10 meters to feet, units will print

* 32.808399
/ 0.03048

which tells you that 10 meters equals about 32.8 feet ๐ŸŽ€. the second number gives the conversion in the opposite direction. in this case it's telling you that 1 foot is equal to about 0.03 dekameters, since the dekameter is 10 meters. it also tells you that 1/32.8 is about 0.03.

the units program prints the inverse because sometimes it's just the more convenient number, okay?? in the example above, the inverse value is an exact conversion: a foot is exactly 0.03048 dekameters. but the number given in the other direction is inexact. the way that matters ๐Ÿ’…

if you convert grains to pounds, you'll see the following:

You have: grains
You want: pounds
        * 0.00014285714
        / 7000

from that second line of output you can immediately see that a grain is equal to a seven thousandth of a pound. not so obvious from the first line, right? if the output format is confusing you, try the --verbose option:

You have: grain
You want: aeginamina
        grain = 0.00010416667 aeginamina
        grain = (1 / 9600) aeginamina

if you request a conversion between units that measure reciprocal dimensions, units will display the results with an extra lil note saying a reciprocal conversion has been done:

You have: 6 ohms
You want: siemens
        reciprocal conversion
        * 0.16666667
        / 6

reciprocal conversion can be suppressed with the --strict option. and as usual, --verbose gets you more comprehensible output:

You have: tex
You want: typp
        reciprocal conversion
        1 / tex = 496.05465 typp
        1 / tex = (1 / 0.0020159069) typp
You have: 20 mph
You want: sec/mile
        reciprocal conversion
        1 / 20 mph = 180 sec/mile
        1 / 20 mph = (1 / 0.0055555556) sec/mile

if you enter incompatible unit types, the units program will print a message telling you the units are not conformable, and it'll show you the reduced form for each unit:

You have: ergs/hour
You want: fathoms kg^2 / day
conformability error
        2.7777778e-11 kg m^2 / sec^3
        2.1166667e-05 kg^2 m / sec

if you only wanna find the reduced form or definition of a unit, just hit Enter at the You want: prompt. example time:

You have: jansky
You want:
        Definition: fluxunit = 1e-26 W/m^2 Hz = 1e-26 kg / s^2

that output tells you the jansky is defined to be equal to a fluxunit, which is itself defined to be a certain combination of watts, meters, and hertz. the fully reduced (and in this case kinda more cryptic) form shows up on the far right. and if the ultimate definition and the fully reduced form are identical, the latter isn't shown at all:

You have: B
You want:
        Definition: byte = 8 bit

the fully reduced form DOES show up if it and the ultimate definition are equivalent but not identical:

You have: N
You want:
        Definition: newton = kg m / s^2 = 1 kg m / s^2

some named units are treated as dimensionless in some situations. these include the radian and steradian. in units conversions they get treated as equal to 1. power equals torque times angular velocity, and that conversion can only happen if the radian is dimensionless:

You have: (14 ft lbf) (12 radians/sec)
You want: watts
        * 227.77742
        / 0.0043902509

you can also compute roots and other non-integer powers of dimensionless units, which lets you do computations like the altitude of geosynchronous orbit ๐ŸŒˆ:

You have: cuberoot(G earthmass / (circle/siderealday)^2) - earthradius
You want: miles
        * 22243.267
        / 4.4957425e-05
โš ๏ธ named dimensionless units are NOT treated as dimensionless in other contexts, bestie. they can't be used as exponents โ€” so for example, meter^radian is forbidden. do not try her.

if you want a list of options, type ? at the You want: prompt. the program will show a list of named units that are conformable with the unit you entered at the You have: prompt above. note: conformable unit combinations will not appear on this list. okayyy ๐Ÿ‘‘


๐ŸŽ€ Interactive Commands ๐ŸŽ€

typing help at either prompt displays a short help message. you can also type help followed by a unit name โ€” this invokes a pager on the units database at the point where that unit is defined, so you can read the definition and any comments that give more details or historical info about the unit ๐Ÿ“–. if your pager allows it, you may wanna scroll backwards, e.g. with b, because sometimes a longer comment about a unit or group of units appears before the definition. you can generally quit out of the pager by pressing q.

typing search text displays a list of all units whose names contain text as a substring, along with their definitions. super helpful when you're not sure of the right unit name ๐Ÿ™ˆ. typing search . displays a list of all units โ€” helpful if you can't come up with an appropriate substring, though examining the output can be tedious, ngl. here . is a special argument to the search command, not a regular expression. if you DO want to use a regular expression to search units and their definitions, the --list-units option will display a list of all units, which you can pipe to a filter like grep. typing search _ displays a list of all assigned runtime variables โ€” whose names begin with _ โ€” without including all the units whose names simply contain _. see Variables Assigned at Run Time for more on runtime variables.

typing version displays the units version number; and unlike the --version option, only the version number is shown, regardless of any other settings. full information is available with the info command.

typing info displays the same information as the --info option, described in Invoking Units.

many values set by command-line options can also be set interactively by typing set option=value; typing set option will show the value for that option. typing set shows a list of options that can be set, and options set to anything other than their default values get a * prepended โญ. see Setting Options Interactively for more.


๐Ÿ’… USING UNITS NON-INTERACTIVELY ๐Ÿ’…

okay so bestie, you don't have to sit there chatting with the prompt all day โ€” units can do the whole conversion thing non-interactively, straight from the command line. how? you just type the command, then the original unit expression, then the new units you want. that's it. that's the whole vibe.

quick heads up tho: if a units expression has non-alphanumeric characters in it, the shell might try to get cute and interpret them, so you may need to protect it with single or double quote characters. ๐Ÿซถ

so if you type

units "2 liters" quarts

then units will print

    * 2.1133764
    / 0.47317647

and then exit. and what that output is telling you is that 2 liters is about 2.1 quarts, or alternatively that a quart is about 0.47 times 2 liters. both readings, one slay conversion. โœจ

and here's the thing โ€” units does not require a space between a numerical value and the unit. so the previous example can just be given as

units 2liters quarts

which saves you from having to quote the first argument at all. no quotes, no stress, no cap. ๐Ÿ’…

if the conversion is successful, units will return success (zero) to the calling environment. but if you enter non-conformable units, then units will print a message giving the reduced form of each unit, and it will return failure (nonzero) to the calling environment. so the exit code is genuinely telling you the tea. ๐Ÿ‘‘

if the --conformable option is given, only one unit expression is allowed, and units will print all units conformable with that expression โ€” it's equivalent to giving ? at the You want: prompt. for example,

units --conformable gauss
B_FIELD   tesla
Gs        gauss
T         tesla
gauss     abvolt sec / cm^2
stT       stattesla
statT     stattesla
stattesla statWb/cm^2
tesla     Wb/m^2

look at all those conformable friends. the way they all match up?? iconic. ๐ŸŒˆ

โš ๏ธ if you give more than one unit expression with the --conformable option, the program will exit with an error message and return failure. one expression only, bestie. also note: this option has no effect in interactive mode.

and if the --terse (-t) option is given with the --conformable option, conformable units are shown without definitions. with the previous example, this would give

units --terse --conformable gauss
B_FIELD
Gs
T
gauss
stT
statT
stattesla
tesla

just the names, no explanations. minimal. clean. it's giving less is more. ๐ŸŽ€

when the --conformable option is not given and you invoke units with only one argument, units will print the definition of the specified unit. it will return failure if the unit is not defined, and success if the unit is defined. so yeah โ€” one argument = definition reveal. ๐Ÿฆ‹


๐Ÿ” Finding Units ๐Ÿ”

so the units database includes many units, and ngl it can sometimes be difficult to remember every single name. the interactive search command only examines unit names, so it cannot be used to find units whose definitions contain a pattern. tragic, ik. ๐Ÿ˜ญ

but!! if units is invoked with the --list-units option, the output can be sent to a filter such as grep, examining the unit name and the definition. for example,

units --list-units | grep ';'
dms                                    deg;arcmin;arcsec
ftin                                   ft;in;1|8 in
ftin16                                 ft;in;1|16 in
ftin32                                 ft;in;1|32 in
ftin4                                  ft;in;1|4 in
ftin64                                 ft;in;1|64 in
ftin8                                  ft;in;1|8 in
hms                                    hr;min;sec
inchfine                               in;1|8 in;1|16 in;1|32 in;1|64 in
time                                   year;day;hr;min;sec
uswt                                   lb;oz
  .  .  .

could find all unit lists, which include at least one semicolon in their definitions. semicolon girlies rise up. ๐Ÿ’œ

the search command doesn't support regular expressions, but with the --list-units option the output can be sent to a filter such as grep, which does. and if you expect a long list of results, you can send the output of the filter to a pager. for example,

units --list-units | grep 'paper[[:space:]]' | more
A0paper                                841 mm 1189 mm
A10paper                               26 mm 37 mm
A1paper                                594 mm 841 mm
A2paper                                420 mm 594 mm
A3paper                                297 mm 420 mm
A4paper                                210 mm 297 mm
A5paper                                148 mm 210 mm
A6paper                                105 mm 148 mm
A7paper                                74 mm 105 mm
A8paper                                52 mm 74 mm
A9paper                                37 mm 52 mm
  .  .  .

could show a list of all defined paper sizes. every paper size ever, piped straight to your eyeballs. obsessed. โœจ

๐Ÿ’– UNIT DEFINITIONS ๐Ÿ’–

okay so bestie, the conversion info is read from several units data files: definitions.units, elements.units, currency.units, and cpi.units, and theyโ€™re usually located in the /usr/share/units directory. If you invoke units with the -V option, it will print the location of these files. The default main file includes definitions for all familiar units, abbreviations and metric prefixes. It also includes many obscure or archaic units. Many common spelled-out numbers (e.g., seventeen) are recognized. ๐Ÿ’…

๐Ÿ’ซ Physical Constants ๐Ÿ’ซ

Many constants of nature are defined, including these:

  • pi โ€” ratio of circumference of a circle to its diameter
  • c โ€” speed of light
  • e โ€” charge on an electron
  • force โ€” acceleration of gravity
  • mole โ€” Avogadroโ€™s number
  • water โ€” pressure per unit height of water
  • Hg โ€” pressure per unit height of mercury
  • au โ€” astronomical unit
  • k โ€” Boltzmanโ€™s constant
  • mu0 โ€” permeability of vacuum
  • epsilon0 โ€” permittivity of vacuum
  • G โ€” Gravitational constant
  • mach โ€” speed of sound

The standard data file includes numerous other constants. Also included are the densities of various ingredients used in baking so that 2 cups flour_sifted can be converted to grams. This is not an exhaustive list. Consult the units data file to see the complete list, or to see the definitions that are used. ๐Ÿง

โš›๏ธ Atomic Masses of the Elements โš›๏ธ

The data file elements.units includes atomic masses for most elements and most known isotopes. If the mole fractions of constituent isotopes are known, an elemental mass is calculated from the sum of the products of the mole fractions and the masses of the constituent isotopes. If the mole fractions are not known, the mass of the most stable isotopeโ€”if knownโ€”is given as the elemental mass. For radioactive elements with atomic numbers 95 or greater, the mass number of the most stable isotope is not specified, because the list of studied isotopes is still incomplete. If no stable isotope is known, no elemental mass is given, and you will need to choose the most appropriate isotope. ๐Ÿ’€

The data are obtained from the US National Institute for Standards and Technology (NIST): https://physics.nist.gov/cgi-bin/Compositions/stand_alone.pl?ele=&all=all&ascii=ascii2&isotype=all. The elements.units file can be generated from these data using the elemcvt command included with the distribution. โœจ

๐Ÿ’ธ Currency Exchange Rates and Consumer Price Index ๐Ÿ’ธ

The data files currency.units, crypto.units, and metal_prices.units include currency conversion rates, cryptocurrency prices, and the prices of precious metals. The file cpi.units includes the US Consumer Price Index (CPI), published by the US Bureau of Labor Statistics; the data are updated monthly by the BLS. See Updating Currency Exchange Rates and CPI for information on updating currency.units, crypto.units, metal_prices.units, and cpi.units. ๐Ÿ’ธ

๐Ÿ‡ฌ๐Ÿ‡ง English Customary Units ๐Ÿ‡บ๐Ÿ‡ธ

English customary units differ in various ways among different regions. In Britain a complex system of volume measurements featured different gallons for different materials such as a wine gallon and ale gallon that differ by twenty percent. This complexity was swept away in 1824 by a reform that created an entirely new gallon, the British Imperial gallon defined as the volume occupied by ten pounds of water. Meanwhile in the USA the gallon is derived from the 1707 Winchester wine gallon, which is 231 cubic inches. These gallons differ by about twenty percent. By default if units runs in the en_GB locale you will get the British volume measures. If it runs in the en_US locale you will get the US volume measures. In other locales the default values are the US definitions. If you wish to force different definitions, then set the environment variable UNITS_ENGLISH to either US or GB to set the desired definitions independent of the locale. ๐Ÿ‡บ๐Ÿ‡ธ๐Ÿ‡ฌ๐Ÿ‡ง

Before 1959, the value of a yard (and other units of measure defined in terms of it) differed slightly among English-speaking countries. In 1959, Australia, Canada, New Zealand, the United Kingdom, the United States, and South Africa adopted the Canadian value of 1 yard = 0.9144 m (exactly), which was approximately halfway between the values used by the UK and the US; it had the additional advantage of making 1 inch = 2.54 cm (exactly). This new standard was termed the International Yard. Australia, Canada, and the UK then defined all customary lengths in terms of the International Yard (Australia did not define the furlong or rod); because many US land surveys were in terms of the pre-1959 units, the US continued to define customary surveyorsโ€™ units (furlong, chain, rod, pole, perch, and link) in terms of the previous value for the foot, which was termed the US survey foot. The US defined a US survey mile as 5280 US survey feet, and defined a statute mile as a US survey mile. The US values for these units differed from the international values by about 2 ppm. ๐Ÿ“

The 1959 redefinition of the foot was legally binding in the US but allowed continued use of the previous definition of the foot for geodetic surveying. It was assumed that this use would be temporary, but use persisted, leading to confusion and errors, and it was at odds with the intent of uniform standards. Since January 1, 2023, the US survey foot has been officially deprecated (85 FR 62698), with its use limited to historical and legacy applications. ๐Ÿšซ

The units program has always used the international values for these units; the legacy US values can be obtained by using either the US or the survey prefix. In either case, the simple familiar relationships among the units are maintained, e.g., 1 furlong = 660 ft, and 1 USfurlong = 660 USft, though the metric equivalents differ slightly between the two cases. The US prefix or the survey prefix can also be used to obtain the US survey mile and the value of the US yard prior to 1959, e.g., USmile or surveymile (but not USsurveymile). To get the US value of the statute mile, use either USstatutemile or USmile. The pre-1959 UK values for these units can be obtained with the prefix UK. ๐Ÿ‘‘

Except for distances that extend over hundreds of miles (such as in the US State Plane Coordinate System), the differences in the miles are usually insignificant:

You have: 100 surveymile - 100 mile
You want: inch
        * 12.672025
        / 0.078913984

The US acre was officially defined in terms of the US survey foot, but units has used a definition based on the international foot; the units definition is now the same as the official US value. If you want the previous US acre, use USacre and similarly use USacrefoot for the previous US version of that unit. The difference between these units is about 4 parts per million. ๐ŸŒฝ

๐Ÿงธ Miscellaneous Notes on Unit Definitions ๐Ÿงธ

The pound is a unit of mass. To get force, multiply by the force conversion unit force or use the shorthand lbf. (Note that g is already taken as the standard abbreviation for the gram.) The unit ounce is also a unit of mass. The fluid ounce is fluidounce or floz. When British capacity units differ from their US counterparts, such as the British Imperial gallon, the unit is defined both ways with br and us prefixes. Your locale settings will determine the value of the unprefixed unit. Currency is prefixed with its country name: belgiumfranc, britainpound. ๐Ÿ’ธ

When searching for a unit, if the specified string does not appear exactly as a unit name, then the units program will try to remove a trailing s, es. Next units will replace a trailing ies with y. If that fails, units will check for a prefix. The database includes all of the standard metric prefixes. Only one prefix is permitted per unit, so micromicrofarad will fail. However, prefixes can appear alone with no unit following them, so micro*microfarad will work, as will micro microfarad. ๐Ÿ”

To find out which units and prefixes are available, read the default units data files; the main data file is extensively annotated. ๐Ÿ“š

๐Ÿงฎ UNIT EXPRESSIONS ๐Ÿงฎ

โž• Operators โž•

You can enter more complicated units by combining units with operations such as multiplication, division, powers, addition, subtraction, and parentheses for grouping. You can use the customary symbols for these operators when units is invoked with its default options. Additionally, units supports some extensions, including high priority multiplication using a space, and a high priority numerical division operator (|) that can simplify some expressions. โœจ

You multiply units using a space or an asterisk (*). The next example shows both forms:

You have: arabicfoot * arabictradepound * force
You want: ft lbf
        * 0.7296
        / 1.370614

You can divide units using the slash (/) or with per:

You have: furlongs per fortnight
You want: m/s
        * 0.00016630986
        / 6012.8727

You can use parentheses for grouping:

You have: (1/2) kg / (kg/meter)
You want: league
        * 0.00010356166
        / 9656.0833

White space surrounding operators is optional, so the previous example could have used (1/2)kg/(kg/meter). As a consequence, however, hyphenated spelled-out numbers (e.g., forty-two) cannot be used; forty-two is interpreted as 40 - 2. ๐Ÿ˜ญ

Multiplication using a space has a higher precedence than division using a slash and is evaluated left to right; in effect, the first / character marks the beginning of the denominator of a unit expression. This makes it simple to enter a quotient with several terms in the denominator: J / mol K. The * and / operators have the same precedence, and are evaluated left to right; if you multiply with *, you must group the terms in the denominator with parentheses: J / (mol * K). ๐Ÿ”ฅ

The higher precedence of the space operator may not always be advantageous. For example, m/s s/day is equivalent to m / s s day and has dimensions of length per time cubed. Similarly, 1/2 meter refers to a unit of reciprocal length equivalent to 0.5/meter, perhaps not what you would intend if you entered that expression. To get a half meter you would need to use parentheses: (1/2) meter. The * operator is convenient for multiplying a sequence of quotients. For example, m/s * s/day is equivalent to m/day. Similarly, you could write 1/2 * meter to get half a meter. ๐Ÿ’…

Okay bestie, buckle up, because the units program has โœจanotherโœจ way to do fractions, and it's lowkey iconic: you can show division of numbers with the vertical bar (|). So if you wanted half a meter, you'd just write 1|2 meter ๐Ÿ’…. But heads up โ€” you cannot use the vertical bar to divide non-numerical units (so m|s is gonna throw an error message at you, no cap ๐Ÿ™ˆ).

Powers of units? Two ways, bestie. Either the ^ character, like in the example below, or just smush a unit and its exponent together: cm3 is equivalent to cm^3. If the exponent is more than one digit though, you have to use the ^. You can also use ** as an exponent operator ๐ŸŽ€.

You have: cm^3
You want: gallons
        * 0.00026417205
        / 3785.4118

Concatenation only works with a single unit name, okay? If you write (m/s)2, units is gonna treat that as multiplication by 2. And when a unit includes a prefix, exponent operators apply to the whole combination, so centimeter3 gives you cubic centimeters ๐Ÿงš. But if you separate the prefix from the unit with any multiplication operator (like centi meter^3), the prefix gets treated as a separate unit, so the exponent only applies to the unit without the prefix. That second one is equivalent to centi * (meter^3), and it gives you a hundredth of a cubic meter โ€” not a cubic centimeter, bestie, they're different!! ๐Ÿ˜ญ

Also the units program is limited internally to products of 99 units, so expressions like meter^100 or joule^34 (which is represented internally as kg^34 m^68 / s^68) will straight-up fail ๐Ÿ’€.

The | operator has the highest precedence, so you can write the square root of two thirds as 2|3^1|2. The ^ operator has the second highest precedence, and it's evaluated right to left, as usual:

You have: 5 * 2^3^2
You want:
        Definition: 2560

With a dimensionless base unit, any dimensionless exponent is meaningful (e.g., pi^exp(2.371)). Even though angle is sometimes treated as dimensionless, exponents cannot have dimensions of angle, periodt:

You have: 2^radian
                 ^
Exponent not dimensionless

If the base unit is not dimensionless, the exponent has to be a rational number p/q, and the dimension of the unit must be a power of q. So gallon^2|3 works but acre^2|3 fails ๐ŸŒธ. An exponent using the slash (/) operator (e.g., gallon^(2/3)) is also acceptable โ€” the parentheses are needed because the precedence of ^ is higher than that of /. And since units cannot represent dimensions with exponents greater than 99, a fully reduced exponent must have q < 100. When you raise a non-dimensionless unit to a power, units attempts to convert a decimal exponent to a rational number with q < 100. If that's not possible, units hits you with an error message:

You have: ft^1.234
Base unit not dimensionless; rational exponent required

A decimal exponent must match its rational representation to machine precision, so acre^1.5 works but gallon^0.666 does not ๐Ÿ‘‘


๐ŸŒˆ Sums and Differences of Units ๐ŸŒˆ

Sometimes you wanna add values of different units that live outside the SI. And sometimes you just wanna use units as a calculator that keeps track of units for you, which is honestly so valid ๐Ÿซถ. Sums of conformable units are written with the + character, and differences with the - character.

You have: 2 hours + 23 minutes + 32 seconds
You want: seconds
        * 8612
        / 0.00011611705

You have: 12 ft + 3 in
You want: cm
        * 373.38
        / 0.0026782366

You have: 2 btu + 450 ft lbf
You want: btu
        * 2.5782804
        / 0.38785542

The expressions that get added or subtracted must reduce to identical expressions in primitive units, or you'll get an error message:

You have: 12 printerspoint - 4 heredium
                                      ^
Invalid sum of non-conformable units

If you add two values of vastly different scale, you may exceed the available precision of floating point (about 15 digits). The effect? The addition of the smaller value makes no change to the larger value โ€” in other words, the smaller value is treated as if it were zero ๐Ÿ˜ญ.

You have: lightyear + cm

No warning is given, however ๐Ÿ’€. As usual, the precedence for + and - is lower than that of the other operators. A fractional quantity like 2 1/2 cups can be given as (2+1|2) cups โ€” the parentheses are necessary because multiplication has higher precedence than addition. If you omit the parentheses, units attempts to add 2 and 1|2 cups, and you get an error message:

You have: 2+1|2 cups
                   ^
Invalid sum or difference of non-conformable units

You could also correctly write it as (2+1/2) cups. But if you write 2 1|2 cups, the space is interpreted as multiplication, so the result is the same as 1 cup ๐Ÿ™ˆ.

The + and - characters sometimes appear in exponents like 3.43e+8. This leads to an ambiguity in an expression like 3e+2 yC. The unit e is a small unit of charge, so this can be regarded as equivalent to (3e+2) yC or (3 e)+(2 yC). This ambiguity is resolved by always interpreting + and - as part of an exponent if possible โœจ.


๐Ÿ”ข Numbers as Units ๐Ÿ”ข

For units, numbers are just another kind of unit, bestie. They can appear as many times as you like and in any order in a unit expression. For example, to find the volume of a box that is 2 ft by 3 ft by 12 ft in steres, you could do this:

You have: 2 ft 3 ft 12 ft
You want: stere
        * 2.038813
        / 0.49048148
You have: $ 5 / yard
You want: cents / inch
        * 13.888889
        / 0.072

And that second example shows how the dollar sign in the units conversion can precede the five ๐Ÿ’…. But be careful: units will interpret $5 with no space as equivalent to dollar^5. Sneaky!!


๐ŸŽ€ Built-in Functions ๐ŸŽ€

Several built-in functions are provided: sin, cos, tan, secant, csc, cot, asin, acos, atan, asecant, acsc, acot, sinh, cosh, tanh, sech, csch, coth, asinh, acosh, atanh, asech, acsch, acoth, exp, ln, log, abs, round, floor, ceil, factorial, Gamma, lnGamma, erf, and erfc. The function lnGamma is the natural logarithm of the Gamma function ๐Ÿงฎ.

The sin, cos, tan, secant, csc and cot functions require either a dimensionless argument or an argument with dimensions of angle.

You have: sin(30 degrees)
You want:
        Definition: 0.5
You have: sin(pi/2)
You want:
        Definition: 1
You have: sin(3 kg)
                  ^
Unit not dimensionless

The other functions on the list require dimensionless arguments. And the inverse trigonometric functions return arguments with dimensions of angle ๐ŸŒธ.

The ln and log functions give natural log and log base 10 respectively. To obtain logs for any integer base, enter the desired base immediately after log. So for log base 2 you'd write log2, and for log base 47 you could write log47 โญ.

You have: log2(32)
You want:
        Definition: 5
You have: log3(32)
You want:
        Definition: 3.1546488
You have: log4(32)
You want:
        Definition: 2.5
You have: log32(32)
You want:
        Definition: 1
You have: log(32)
You want:
        Definition: 1.50515
You have: log10(32)
You want:
        Definition: 1.50515

If you wish to take roots of units, you may use the sqrt or cuberoot functions. These functions require that the argument have the appropriate root. You can obtain higher roots by using fractional exponents ๐ŸŒˆ:

You have: sqrt(acre)
You want: feet
        * 208.71074
        / 0.0047913202
You have: (400 W/m^2 / stefanboltzmann)^(1/4)
You have:
        Definition: 289.80882 K
You have: cuberoot(hectare)
                          ^
Unit not a root

๐Ÿ’– Previous Result ๐Ÿ’–

You can insert the result of the previous conversion using the underscore (_). It's useful when you wanna convert the same input to several different units, like this:

You have: 2.3 tonrefrigeration
You want: btu/hr
        * 27600
        / 3.6231884e-005
You have: _
You want: kW
        * 8.0887615
        / 0.12362832

Suppose you wanna do some deep frying that requires an oil depth of 2 inches. You have 1/2 gallon of oil, and want to know the largest-diameter pan that will maintain the required depth. The nonlinear unit circlearea gives the radius of the circle (see Other Nonlinear Units, for a more detailed description) in SI units; you want the diameter in inches:

You have: 1|2 gallon / 2 in
You want: circlearea
        0.10890173 m
You have: 2 _
You want: in
        * 8.5749393
        / 0.1166189

In most cases, surrounding white space is optional, so the previous example could have used 2_. If _ follows a non-numerical unit symbol, however, the space is required:

You have: m_
           ^
Parse error

You can use the _ symbol any number of times; for example,

You have: m
You want:
        Definition: 1 m
You have: _ _
You want:
        Definition: 1 m^2

Using _ before a conversion has been performed (e.g., immediately after invocation) generates an error:

You have: _
          ^
No previous result; '_' not set

Accordingly, _ serves no purpose when units is invoked non-interactively ๐Ÿ’€.

If units is invoked with the --verbose option (see Invoking Units), the value of _ is not expanded:

You have: mile
You want: ft
        mile = 5280 ft
        mile = (1 / 0.00018939394) ft
You have: _
You want: m
        _ = 1609.344 m
        _ = (1 / 0.00062137119) m

You can give _ at the You want: prompt, but it usually is not very useful ๐Ÿ™ˆ.


๐Ÿฆ‹ Complicated Unit Expressions ๐Ÿฆ‹

The units program is especially helpful in ensuring accuracy and dimensional consistency when converting lengthy unit expressions, and honestly? That's the moment. ๐Ÿ‘‘

For example, one form of the Darcy-Weisbach fluid-flow equation is

Delta P = (8 / pi)^2 (rho fLQ^2) / d^5,

where Delta P is the pressure drop, rho is the mass density, f is the (dimensionless) friction factor, L is the length of the pipe, Q is the volumetric flow rate, and d is the pipe diameter. You might want to have the equation in the form

Delta P = A1 rho fLQ^2 / d^5

that was like, accepting the user's normal units, bestie. For the typical units used in the US, the conversion you need could be something like

You have: (8/pi^2)(lbm/ft^3)ft(ft^3/s)^2(1/in^5)
You want: psi
        * 43.533969
        / 0.022970568

The parentheses let you drop individual terms into the expression naturally, exactly like you'd read them off the formula. โœจ Or, you could do the multiplication with * instead of a space โ€” and then you only need parens around ft^3/s because of that little exponent situation:

You have: 8/pi^2 * lbm/ft^3 * ft * (ft^3/s)^2 /in^5
You want: psi
        * 43.533969
        / 0.022970568

No parentheses and using spaces for multiplication, the same conversion would need to be typed as

You have: 8 lb ft ft^3 ft^3 / pi^2 ft^3 s^2 in^5
You want: psi
        * 43.533969
        / 0.022970568

๐ŸŒธ Variables Assigned at Run Time ๐ŸŒธ

Unit definitions are locked in once units has finished reading the units data file(s) โ€” no takebacks, no edits. BUT at run time you can assign unit expressions to variables whose names begin with an underscore, using this syntax:

_name = <unit expression>

This is lowkey a lifesaver for managing a long calculation โ€” you save intermediate quantities as variables and reuse them later. ๐Ÿ’… For example, to find the shot-noise-limited signal-to-noise ratio (SNR) of an imaging system using a heliumโ€“neon laser, you could do

You have: _lambda = 632.8 nm            # laser wavelength
You have: _nu = c / _lambda             # optical frequency
You have: _photon_energy = h * _nu
You have: _power = 550 uW
You have: _photon_count = _power * 500 ns / _photon_energy
You have: _snr = sqrt(_photon_count)
You have: _snr
You want:
        Definition: sqrt(_photon_count) = 29597.922

Other than the underscore at the front, runtime variables follow the exact same naming rules as units. And because names starting with _ are reserved for these variables, and unit names can't start with _, runtime variables can never hide unit definitions. ๐Ÿซถ Runtime variables are undefined until you actually assign something to them, so if you type a name starting with an underscore and no assignment has happened yet, you get an error message.

When you assign a unit expression to a runtime variable, units checks the expression to make sure it's valid, but the resulting definition is stored as a text string that is not reduced to primitive units. That text gets processed anew every single time you use the variable in a conversion or calculation. Which means: if your definition depends on other runtime variables (or the special variable _), the result of calculating with your variable will change if any of those variables change. And the dependence doesn't even need to be direct. ๐Ÿ˜ญ

Continuing the laser example above โ€” say you've done the calculation as shown. Now you're wondering what happens if you switch to an argon laser:

You have: _lambda = 454.6 nm
You have: _snr
You want:
        Definition: sqrt(_photon_count) = 25086.651

And if you then change the power:

You have: _power = 1 mW
You have: _snr
You want:
        Definition: sqrt(_photon_count) = 33826.834

Instead of having to reenter or edit some lengthy expression every time you do another calculation, you only need to enter the values that change. In this respect, runtime variables are basically a spreadsheet. ๐Ÿ“Šโœจ

The more times a variable shows up in an expression that depends on it, the bigger the payoff of having a calculation with that expression reflect changes to that variable. For example, the length of daylight โ€” the time the Sun is above the horizon โ€” at a given latitude and declination of the Sun is given by

L = acos((sin h - sin ฯ• sin ฮด) /
               (cos ฯ• cos ฮด))

where L is the day length, h is the altitude, ฯ• is the latitude, and ฮด is the Sun's declination.

The result above is in sidereal time; the length in solar time is obtained by multiplying by

siderealday / day

By convention, the Sun's altitude at rise or set is -50โ€ฒ to allow for atmospheric refraction and the semidiameter of its disk. At the summer solstice in the northern hemisphere, the Sun's declination is approximately 23.44ยฐ; to find the length of the longest day of the year for a latitude of 55ยฐ, you could do

You have: _alt = -50 arcmin
You have: _lat = 55 deg
You have: _decl = 23.44 deg
You have: _num = sin(_alt) - sin(_lat) sin(_decl)
You have: _denom = cos(_lat) cos(_decl)
You have: _sday = 2 (acos(_num / _denom) / circle) 24 hr
You have: _day = _sday siderealday / day
You have: _day
You want: hms
        17 hr + 19 min + 34.895151 sec

At the winter solstice, the Sun's declination is approximately -23.44ยฐ, so you could calculate the length of the shortest day of the year using:

You have: _decl = -23.44 deg
You have: _day
You want: hms
        7 hr + 8 min + 40.981084 sec

Latitude and declination each appear twice in the expression for _day; the result in the examples above updates by changing only the value of the declination. ๐Ÿงš

Now โ€” it might seem easier (and less error-prone) to just specify the new value of _decl as the negative of the current value (like, _decl = -_decl). This doesn't work. When you make an assignment with the = operator, the definition is stored as entered, including possible dependencies on variables. But if you attempt an assignment that's ultimately self-referential, the current definition is retained, and you get an error message. For example,

You have: _decl = 23.44 deg
You have: _decl = -_decl
Circular unit definition

You can get around this with the := operator, which reduces the right hand side to primitive units before making the assignment โ€” eliminating any dependencies on variables. Back to the example:

You have: _decl = 23.44 deg
You have: _decl = -_decl
Circular unit definition
You have: _decl := -_decl
You have: _decl
You want: deg
        * -23.44
        / -0.042662116

This works to much the same effect as if the assignment had been entered literally, e.g.,

You have: _decl = -23.44 deg

but the actual definition is in primitive units โ€” in this case, radians:

You have: _decl = 23.44 deg
You have: _decl := -_decl
You have: _decl
You want:
        Definition: -0.40910517666747087 radian = -0.40910518 radian

Definitions are text strings, and a redefinition using := is given with enough digits to maintain the full precision of the current definition when converted back to a number; because it's a string, all digits are displayed when showing the definition, regardless of the numerical display precision, so you may see more digits than you expected. ๐Ÿ‘€

A runtime variable has to be assigned before it can be used in an assignment โ€” in the first of the three examples above, giving the general equation before the values for _alt, _lat, and _decl had been assigned would result in an error message.

You can display a list of runtime variables you've assigned by typing search _.


๐Ÿ’€ Backwards Compatibility: * and - ๐Ÿ’€

The original units gave multiplication a higher precedence than division using the slash. This differs from the usual precedence rules, which give multiplication and division equal precedence, and can be confusing for people who think of units as a calculator.

The star operator (*) included in this units program has, by default, the same precedence as division, and therefore follows the usual precedence rules. For backwards compatibility you can invoke units with the --oldstar option. Then * has a higher precedence than division, and the same precedence as multiplication using the space.

Historically, the hyphen (-) has been used in technical publications to indicate products of units, and the original units program treated it as a multiplication operator. Because units provides several other ways to obtain unit products, and because - is a subtraction operator in general algebraic expressions, units treats the binary - as a subtraction operator by default. For backwards compatibility use the --product option, which causes units to treat the binary - operator as a product operator. When - is a multiplication operator it has the same precedence as multiplication with a space, giving it a higher precedence than division.

When - is used as a unary operator it negates its operand. Regardless of the units options, if - appears after ( or after +, then it will act as a negation operator. So you can always compute 20 degrees minus 12 minutes by entering 20 degrees + -12 arcmin. You must use this construction when you define new units, because you cannot know what options will be in force when your definition is processed. โš ๏ธ


๐ŸŒˆ NONLINEAR UNIT CONVERSIONS ๐ŸŒˆ

Nonlinear units are represented using functional notation. They make possible nonlinear unit conversions such as temperature. ๐Ÿฅต๐Ÿฅถ

๐ŸŽ€ Temperature Conversions ๐ŸŽ€

Conversions between temperatures are different from linear conversions between temperature increments โ€” see the example below. The absolute temperature conversions are handled by units starting with temp, and you must use functional notation. The temperature-increment conversions are done using units starting with deg and they do not require functional notation.

You have: tempF(45)
You want: tempC
        7.2222222
You have: 45 degF
You want: degC
        * 25
        / 0.04

Think of tempF(x) not as a function but as a notation that indicates that x should have units of tempF attached to it. See Defining Nonlinear Units. The first conversion shows that if it's 45 degrees Fahrenheit outside, it's 7.2 degrees Celsius. The second conversion indicates that a change of 45 degrees Fahrenheit corresponds to a change of 25 degrees Celsius. The conversion from tempF(x) is to absolute temperature, so that

You have: tempF(45)
You want: degR
        * 504.67
        / 0.0019814929

gives the same result as

You have: tempF(45)
You want: tempR
        * 504.67
        / 0.0019814929

But if you convert tempF(x) to degC, the output is probably not what you expect:

You have: tempF(45)
You want: degC
        * 280.37222
        / 0.0035666871

The result is the temperature in K, because degC is defined as K, the kelvin. For consistent results, use the tempX units when converting to a temperature rather than converting a temperature increment. ๐Ÿ’…โœจ

The tempC() and tempF() definitions are strictly limited to positive absolute temperatures, bestie. Hand them a value that would land you at a negative absolute temperature and they will absolutely drag you with an error message:

You have: tempC(-275)
                    ^
Argument of function outside domain

๐ŸŒธ US Consumer Price Index ๐ŸŒธ

units ships with the US Consumer Price Index published by the US Bureau of Labor Statistics, no cap. There's a whole lil friend group of functions riding on it: cpi, cpi_now, inflation_since, and dollars_in.

The cpi function hands you the CPI for a specified decimal year. A decimal year is literally just the year plus the fractional chunk of the year โ€” and because of leap years and months being wildly different lengths, working out an exact fractional value is tedious af, but for CPI purposes an approximate value is usually plenty. For example: 1 January 2000 is 2000.0, 1 April 2000 is 2000.25, 1 July 2000 is 2000.4986, and 1 October 2000 is 2000.75. Also worth knowing: the CPI data update monthly, and values in between months are linearly interpolated. โœจ

In the middle of 1975, the CPI was

You have: cpi(1975.5)
You want:
        Definition: 53.6

The value of the CPI for a month usually gets published sometime around the 20th day of the following month, and the latest value is available with cpi_now. On 7 January 2024, the value was

You have: cpi_now
You want:
        Definition: UScpi_now = 307.051

This means that the CPI was 307.015 on 1 December 2023. The cpi_now variable can only present the most recent data available, so it can lag the current CPI by several weeks. The decimal year of the last update is available with cpi_lastdate. ๐Ÿ’…

The inflation_since function is the convenient lil shortcut for figuring out the inflation factor from a specified decimal year to the latest value in the CPI table. For example, on 7 January 2024:

You have: inflation_since(1970)
You want:
        Definition: 8.1445889

In other words, goods that cost 1 US$ in 1970 would cost 8.14 US$ on 1 December 2023. ๐Ÿซถ

You can also use inflation_since to work out an annual rate of inflation. The earliest US CPI data are from about 1913.1; the approximate time between then and 7 January 2024 is 110.9 years. The approximate annual inflation rate for that period is then

You have: inflation_since(1913.1)^1|110.9 - 1
You want: %
        * 3.1548115
        / 0.31697614

And the inflation rate for any time period can be found from the ratio of the CPI at the end of the period to that of the beginning:

You have: (cpi(1982)/cpi(1972))^1|10 - 1
You want: %
        * 8.6247033
        / 0.11594602

The period 1972โ€“1982 was indeed one of high inflation, bestie. ๐Ÿ˜ญ

The dollars_in function is basically inflation_since's sibling, except its output is in US$ rather than dimensionless:

You have: dollars_in(1970)
You want:
        Definition: 8.1445889 US$

A typical use might be

You have: 250 dollars_in(1970)
You want: $
        * 2036.1472
        / 0.00049112362

Because dollars_in already includes the units, you should not include them at the You have: prompt. You can also use dollars_in to convert between two specified years:

You have: 250 dollars_in(1970)
You want: dollars_in(1950)
        * 156.49867
        / 0.0063898305

which shows that 250 US$ in 1970 would have equivalent purchasing power to 156 US$ in 1950. iconic tbh ๐ŸŽ€


๐Ÿฆ‹ Other Nonlinear Units ๐Ÿฆ‹

Some other examples of nonlinear units are numerous different ring sizes and wire gauges, screw gauges, pipe and tubing sizes, the grit sizes used for abrasives, the decibel scale, shoe size, scales for the density of sugar (e.g., baume). The standard data file also supplies units for computing the area of a circle and the volume of a sphere. See the standard units data file for more details. ๐Ÿ‘‘

Diameters of American wire sizes can be found using the wiregauge() function or its alias awg():

You have: wiregauge(11)
You want: inches
        * 0.090742002
        / 11.020255
You have: 1 mm
You want: wiregauge
        18.201919

Wire and screw gauges with multiple zeroes are signified using negative numbers, where two zeroes (โ€œ00โ€; โ€œ2/0โ€) is -1, three zeros (โ€œ000โ€; โ€œ3/0โ€) is -2, and so on. Alternatively, you can use the synonyms g00, g000, or g2_0, g3_0, and so on that are defined in the standard units data file.

You have: brwiregauge(g00)
You want: inches
        * 0.348
        / 2.8735632

In North America, wire sizes larger than 0000 (โ€œ4/0โ€) are usually given in terms of area, either in kcmil or the older initialism MCM (thousand circular mils). Outside of North America, all wire sizes are usually given in terms of area in mm^2. Wire area can be obtained using wiregaugeA() or its alias awgA():

You have: awgA(g6_0)
You want: kcmil
        * 336.45718
        / 0.0029721464
You have: awgA(12)
You want: mm^2
        * 3.3087729
        / 0.30222685

The closest standard metric sizes are 2.5 mm^2 and 4 mm^2; in general, there isn't an exact correlation between American and metric wire sizes. ๐Ÿคท

Though it's based on the long-established iron pipe size (IPS) given in inches, nominal pipe size (NPS) is a dimensionless quantity that corresponds to the inch size. Pipe size can be equivalently specified using metric diamรจtre nominal (DN), which roughly corresponds to the diameter in mm. For a given pipe size, outside diameter is constant while inside diameter varies with schedule. For example, for NPS 2ยฝ pipe,

You have: npsOD(2+1|2)
You want: in
        * 2.875
        / 0.34782609
You have: nps40(2+1|2)
You want: in
        * 2.469
        / 0.40502228
You have: nps80(2+1|2)
You want: in
        * 2.323
        / 0.43047783

Pipe size can be given equivalently in terms of the metric DN by using the DN() function, which converts nominal metric size to nominal inch size:

You have: npsOD(DN(65))
You want: mm
        * 73.025
        / 0.01369394
You have: _
You want: in
        * 2.875
        / 0.34782609

Unlike with wire sizes, actual NPS and metric DN pipe dimensions are the same. ๐Ÿ’–

You have: grit_P(600)
You want: grit_ansicoated
        342.76923

The last example shows the conversion from P graded sand paper, which is the European standard and may be marked โ€œP600โ€ on the back, to the USA standard.

You can compute the area of a circle using the nonlinear unit, circlearea. You can also do this using the circularinch or circleinch. The next example shows two ways to compute the area of a circle with a five inch radius and one way to compute the volume of a sphere with a radius of one meter.

You have: circlearea(5 in)
You want: in2
        * 78.539816
        / 0.012732395
You have: 10^2 circleinch
You want: in2
        * 78.539816
        / 0.012732395
You have: spherevol(meter)
You want: ft3
        * 147.92573
        / 0.0067601492

The inverse of a nonlinear conversion is indicated by prefixing a tilde (~) to the nonlinear unit name:

You have: ~wiregauge(0.090742002 inches)
You want:
        Definition: 11

You can give a nonlinear unit definition without an argument or parentheses, and press Enter at the You want: prompt to get the definition of a nonlinear unit; if the definition is not valid for all real numbers, the range of validity is also given. If the definition requires specific units this information is also displayed:

You have: tempC
        Definition: tempC(x) = x K + stdtemp
                    defined for x >= -273.15
You have: ~tempC
        Definition: ~tempC(tempC) = (tempC +(-stdtemp))/K
                    defined for tempC >= 0 K
You have: circlearea
        Definition: circlearea(r) = pi r^2
                    r has units m

To see the definition of the inverse use the ~ notation. In this case the parameter in the functional definition will usually be the name of the unit. Note that the inverse for tempC shows that it requires units of K in the specification of the allowed range of values. Nonlinear unit conversions are described in more detail in Defining Nonlinear Units. ๐ŸŒˆ


๐Ÿ’€ Multivariate Functions ๐Ÿ’€

The units program supports some multivariate functions for performing calculations with units. The hypot function computes the length of a hypotenuse given two sides. It works with any pair of values that have compatible dimensions.

You have: hypot(3 m, 4 m)
You want:
        Definition: 5 m

You can compute wind chill, based on temperature and wind speed, or heat index, based on temperature and humidity, with humidity given as a fraction, e.g., 0.5 for a 50% relative humidity.

You have: windchill(tempF(28), 14 mph)
You want: tempF
        16.86826
You have: heatindex(tempC(40),0.5)
You want: tempC
        54.767952

Both wind chill and heat index return a value that is nominally a temperature, so you will want to convert it to Fahrenheit or Celsius as shown in order to get a meaningful numerical value. ๐Ÿงš

โœจ UNIT LISTS: CONVERSION TO SUMS OF UNITS โœจ

okay bestie so outside of the SI system, sometimes you genuinely want to turn one unit into a sum of units โ€” like, feet into feet <em>plus</em> inches. the conversion from sums of units was already covered in Sums and Differences of Units, and honestly it's not that deep โ€” you just add the units with the โ€˜+โ€™ sign:

You have: 12 ft + 3 in + 3|8 in
You want: ft
        * 12.28125
        / 0.081424936

and yeah, you can write a sum of units on the "You want:" side too, but heads up โ€” the result won't be the conversion to the units in the sum, it'll be the conversion to that particular sum you typed. so:

You have: 12.28125 ft
You want: ft + in + 1|8 in
        * 11.228571
        / 0.089058524

the unit expression at the โ€˜You want:โ€™ prompt is equivalent to asking for conversion to multiples of โ€˜1 ft + 1 in + 1|8 inโ€™, which is 1.09375 ft, so that whole thing is really just:

You have: 12.28125 ft
You want: 1.09375 ft
        * 11.228571
        / 0.089058524

when you're converting to a sum of units like miles, feet and inches, what you actually want is the largest integral value for the first unit, then the largest integral value for the next, and whatever's left over goes to the last unit. units has a special syntax for lists of units that does this for you ๐ŸŽ€. you must list the desired units in order from largest to smallest, separated by the semicolon (โ€˜;โ€™) character:

You have: 12.28125 ft
You want: ft;in;1|8 in
        12 ft + 3 in + 3|8 in

the conversion always gives integer coefficients on the units in the list โ€” <em>except possibly the last unit</em>, when the conversion isn't exact:

You have: 12.28126 ft
You want: ft;in;1|8 in
        12 ft + 3 in + 3.00096 * 1|8 in

and the order you list them in matters, no cap:

You have: 3 kg
You want: oz;lb
        105 oz + 0.051367866 lb
You have: 3 kg
You want: lb;oz
        6 lb + 9.8218858 oz

listing ounces before pounds gives you a result that's technically correct but likeโ€ฆ not useful? ๐Ÿ’€ you have to list the units in descending order of size to get the most useful result.

ending a unit list with the separator โ€˜;โ€™ has the same effect as repeating the last unit on the list, so โ€˜ft;in;1|8 in;โ€™ is equivalent to โ€˜ft;in;1|8 in;1|8 inโ€™. with the example above, that gives:

You have: 12.28126 ft
You want: ft;in;1|8 in;
        12 ft + 3 in + 3|8 in + 0.00096 * 1|8 in

which basically separates the integer and fractional parts of the coefficient for the last unit. if you'd rather <em>round</em> that last coefficient to an integer, the โ€˜--roundโ€™ (โ€˜-rโ€™) option is right there. same example, and you get:

You have: 12.28126 ft
You want: ft;in;1|8 in
        12 ft + 3 in + 3|8 in (rounded down to nearest 1|8 in)

when you use โ€˜-rโ€™, repeating the last unit on the list has no effect (like, โ€˜ft;in;1|8 in;1|8 inโ€™ is equivalent to โ€˜ft;in;1|8 inโ€™), and so ending a list with a โ€˜;โ€™ does nothing either. but with a single unit and the โ€˜-rโ€™ option, a terminal โ€˜;โ€™ does have an effect: it makes units treat the single unit as a list and produce a rounded value for it. without that extra โ€˜;โ€™, the โ€˜-rโ€™ option has no effect on single unit conversions. here's the output with โ€˜-rโ€™:

You have: 12.28126 ft
You want: in
        * 147.37512
        / 0.0067854058
You have: 12.28126 ft
You want: in;
        147 in (rounded down to nearest in)

every unit in the list has to be conformable with the first unit on the list, and obviously the listed units also have to be conformable with whatever you entered at the โ€˜You have:โ€™ prompt.

You have: meter
You want: ft;kg
             ^
conformability error
        ft = 0.3048 m
        kg = 1 kg
You have: meter
You want: lb;oz
conformability error
        1 m
        0.45359237 kg

in the first case, units reports the disagreement <em>between units appearing on the list</em>. in the second, units reports disagreement between <em>the unit you entered and the desired conversion</em>. and this conformability error is based on the first unit on the unit list, fyi.

other common candidates for conversion to sums of units are angles and time:

You have: 23.437754 deg
You want: deg;arcmin;arcsec
    23 deg + 26 arcmin + 15.9144 arcsec
You have: 7.2319 hr
You want: hr;min;sec
    7 hr + 13 min + 54.84 sec

some applications for unit lists are less obvious ๐Ÿ‘€. say you have a postal scale and you want to make sure it's accurate at 1 oz, but all you have are metric calibration weights. you might try:

You have: 1 oz
You want: 100 g;50 g; 20 g;10 g;5 g;2 g;1 g;
        20 g + 5 g + 2 g + 1 g + 0.34952312 * 1 g

then you'd place one each of the 20 g, 5 g, 2 g, and 1 g weights on the scale and hope it reads close to:

You have: 20 g + 5 g + 2 g + 1 g
You want: oz;
        0.98767093 oz

appending โ€˜;โ€™ to โ€˜ozโ€™ forces a one-line display that includes the unit โ€” here the integer part of the result is zero, so it just doesn't get shown ๐Ÿซถ.

if a non-empty list item differs vastly in scale from the quantity you're converting from, you may blow past the available precision of floating point (about 15 digits), and then you get a warning, like:

You have: lightyear
You want: mile;100 inch;10 inch;mm;micron
        5.8786254e+12 mile + 390 * 100 inch (at 15-digit precision limit)

๐Ÿ“ Cooking Measure ๐Ÿ“

in North America, cooking recipes usually measure ingredients by volume, and use units that aren't always convenient multiples of each other ๐Ÿ˜ญ. suppose you've got a recipe for 6 and you want to make a portion for 1. if the recipe calls for 2 1/2 cups of an ingredient, you might want to know that in terms of the measuring devices you actually own โ€” so you could use units and enter:

You have: (2+1|2) cup / 6
You want: cup;1|2 cup;1|3 cup;1|4 cup;tbsp;tsp;1|2 tsp;1|4 tsp
        1|3 cup + 1 tbsp + 1 tsp

by default, if a unit in a list begins with a fraction of the form 1|x and its multiplier is an integer, the fraction is given as the product of the multiplier and the numerator. for example:

You have: 12.28125 ft
You want: ft;in;1|8 in;
        12 ft + 3 in + 3|8 in

in lots of cases, like the one above, that's exactly what you want โ€” but sometimes it is not. for example, a cooking recipe for 6 might call for 5 1/4 cup of an ingredient, but you want a portion for 2, and your 1-cup measure isn't available. you might try:

You have: (5+1|4) cup / 3
You want: 1|2 cup;1|3 cup;1|4 cup
        3|2 cup + 1|4 cup

and honestly that result might be totally fine for a baker who has a 1 1/2-cup measure (and recognizes the equivalence), but it may not be as useful to someone with a more limited set of measures, who does want to do extra calculations, and only wants to know <em>"How many 1/2-cup measures do I need to add?"</em> โ€” because after all, that's what was actually asked ๐Ÿ’…. with the โ€˜--show-factorโ€™ option, the factor won't be combined with a unity numerator, so you get:

You have: (5+1|4) cup / 3
You want: 1|2 cup;1|3 cup;1|4 cup
        3 * 1|2 cup + 1|4 cup

but a user-specified fractional unit with a numerator other than 1 is never overridden โ€” if a unit list specifies โ€˜3|4 cup;1|2 cupโ€™, a result equivalent to 1 1/2 cups will always be shown as โ€˜2 * 3|4 cupโ€™ whether or not the โ€˜--show-factorโ€™ option is given.

๐ŸŒˆ Unit List Aliases ๐ŸŒˆ

a unit list like

cup;1|2 cup;1|3 cup;1|4 cup;tbsp;tsp;1|2 tsp;1|4 tsp

can be <em>so</em> tedious to type out ๐Ÿ˜ฎโ€๐Ÿ’จ. so the units program gives you shorthand names for some common combinations:

  • hms โ€” time: hours, minutes, seconds
  • dms โ€” angle: degrees, minutes, seconds
  • time โ€” time: years, days, hours, minutes and seconds
  • usvol โ€” US cooking volume: cups and smaller
  • uswt โ€” US weight: pounds and ounces
  • ftin โ€” length: feet, inches and 1/8 inches
  • ftin2 โ€” length: feet, inches and 1/2 inches
  • ftin4 โ€” length: feet, inches and 1/4 inches
  • ftin8 โ€” length: feet, inches and 1/8 inches
  • ftin16 โ€” length: feet, inches and 1/16 inches
  • ftin32 โ€” length: feet, inches and 1/32 inches
  • ftin64 โ€” length: feet, inches and 1/64 inches
  • inchfine โ€” length: inches subdivided to 1/64 inch

using these shorthands โ€” aka unit list aliases โ€” you can do conversions like:

You have: anomalisticyear
You want: time
        1 year + 25 min + 3.4653216 sec
You have: 1|6 cup
You want: usvol
        2 tbsp + 2 tsp

suppose you want to drill a clearance hole for a #10 screw and have about 1/64 inch of clearance; you could try:

You have: screwgauge(10) + 1|64 in
You want: ftin64
        13.16 * 1|64 in
You have: _
You want: ftin32
        6.58 * 1|32 in

if a slightly tight fit is acceptable, a 13/64-inch drill would do the job; if not, a 7/32-inch drill would work with a slightly looser fit. ๐Ÿ”ฅ

you can define your own unit list aliases too โ€” see Defining Unit List Aliases.

important: you cannot combine a unit list alias with other units. it has to appear <em>alone</em> at the โ€˜You want:โ€™ prompt.

you can display the definition of a unit list alias by entering it at the โ€˜You have:โ€™ prompt:

You have: dms
        Definition: unit list, deg;arcmin;arcsec

when you specify compact output with โ€˜--compactโ€™, โ€˜--terseโ€™ or โ€˜-tโ€™ and convert to a unit list, units lists the conversion factors for each unit in the list, separated by semicolons:

You have: year
You want: day;min;sec
365;348;45.974678

and unlike the case of regular output, zeros are included in this output list:

You have: liter
You want: cup;1|2 cup;1|4 cup;tbsp
4;0;0;3.6280454

ALTERNATIVE UNIT SYSTEMS ๐ŸŒˆ

okay bestie, SI is NOT the only game in town. Let's talk alternatives. ๐Ÿ‘‘

CGS Units ๐Ÿ’ซ

So the SI is really just an extension of the older MKS (meterโ€“kilogramโ€“second) system, and it's basically eaten the older CGS (centimeterโ€“gramโ€“second) system alive โ€” but CGS is still living its best life in a few specialized fields, especially physics, where it gives you a way more elegant formulation of Maxwell's equations. โœจ

Conversions between SI and CGS involving mechanical units? Super straightforward, it's all just powers of 10 (like, 1 m = 100 cm, easy). But conversions involving electromagnetic units are messier, and units supports four different CGS systems:

  • electrostatic units (ESU)
  • electromagnetic units (EMU)
  • the Gaussian system
  • the Heavisideโ€“Lorentz system

The tea โ˜• on why they're different: each one made different choices for the proportionality constants in electromagnetic equations.

Coulomb's law gives you the electrostatic force between two charges separated by a distance delim $$ r:

F = k_C q_1 q_2 / r^2.

Ampere's law gives you the electromagnetic force per unit length between two current-carrying conductors separated by a distance r:

F/l = 2 k_A I_1 I_2 / r.

And those two constants, k_C and k_A, are related by the square of the speed of light: k_A = k_C / c^2. ๐Ÿ’…

In the SI, the constants have dimensions, and there's an extra base unit โ€” the ampere โ€” that measures electric current. The CGS systems do NOT define new base units. Instead they express charge and current as derived units in terms of mass, length, and time. So:

  • In the ESU system, the constant for Coulomb's law is chosen to be unity and dimensionless, which defines the unit of charge.
  • In the EMU system, the constant for Ampere's law is chosen to be unity and dimensionless, which defines a unit of current.
  • The Gaussian system usually uses the ESU units for charge and current; it chooses another constant so that the units for the electric and magnetic fields are the same.
  • The Heavisideโ€“Lorentz system is "rationalized" so that factors of 4{pi} do not appear in Maxwell's equations. The SI system is similarly rationalized, but the other CGS systems are not. In the Heavisideโ€“Lorentz (HLU) system the factor of 4{pi} appears in Coulomb's law instead; this system differs from the Gaussian system by factors of the square root of 4{pi}.

The dimensions of electrical quantities in the various CGS systems are different from the SI dimensions for the same units. Strictly speaking? Conversions between these systems and SI are not possible. ๐Ÿ˜ญ But units in different systems relate to the same physical quantities, so there IS a correspondence between them. The units program defines the units so you can convert between corresponding units in the various systems.

Here's the messy part: the CGS definitions involve cm^(1/2) and g^(1/2), which is a whole problem because units doesn't normally support fractional roots of base units. So the --units (-u) option lets you pick a CGS unit system and works around this by introducing base units for the square roots of length and mass: sqrt_cm and sqrt_g. ๐ŸŽ€ The centimeter then becomes sqrt_cm^2 and the gram becomes sqrt_g^2. That way you can work from equations using the units in the CGS system, and enforce dimensional conformity within that system.

Recognized CGS arguments to the --units option are:

  • gauss[ian]
  • esu
  • emu
  • lhu

and the argument is case insensitive. You can also give si, which just enforces the default SI mode and displays (SI) at the You have: prompt to emphasize the units mode. Some other types of units are also supported as described below. If you give an unrecognized system, you get a warning, and units uses SI units.

The changes resulting from the --units option are actually controlled by the UNITS_SYSTEM environment variable. ๐Ÿ‘€

If you frequently work with one of the supported CGS units systems, you may set this environment variable rather than giving the --units option at each invocation. And as usual, an option given on the command line overrides the setting of the environment variable. For example, if you'd normally work with Gaussian units but might occasionally work with SI, you could set UNITS_SYSTEM to gaussian and specify SI with the --units option.

โš ๏ธ BUT. Unlike the argument to the --units option, the value of UNITS_SYSTEM is case sensitive. So setting a value of EMU will have no effect other than to give an error message and set SI units. not me making that mistake ๐Ÿ’€

The CGS definitions appear as conditional settings in the standard units data file, which you can consult for more information on how these units are defined, or on how to define an alternate units system.


The four systems, one by one ๐Ÿซถ

ESU derives the electromagnetic units from its unit of charge, the statcoulomb, which is defined from Coulomb's law. The statcoulomb equals dyne^(1/2) cm, or cm^(3/2) g^(1/2) s^(โˆ’1). The unit of current, the statampere, is statcoulomb sec, analogous to the relationship in SI. Other electrical units are then derived in a manner similar to that for SI units; the units use the SI names prefixed by stat-, e.g., statvolt or statV. The prefix st- is also recognized (e.g., stV).

EMU derives the electromagnetic units from its unit of current, the abampere, which is defined in terms of Ampere's law. The abampere is equal to dyne^(1/2), or cm^(1/2) g^(1/2) s^(โˆ’1). delim off The unit of charge, the abcoulomb, is abampere sec, again analogous to the SI relationship. Other electrical units are then derived in a manner similar to that for SI units; the units use the SI names prefixed by ab-, e.g., abvolt or abV. The magnetic field units include the gauss, the oersted and the maxwell.

Gaussian โ€” which was also known as the Symmetric System โ€” uses the same charge and current units as the ESU system (e.g., statC, statA); it differs by defining the magnetic field so that it has the same units as the electric field. The resulting magnetic field units are the same ones used in the EMU system: the gauss, the oersted and the maxwell.

Heavisideโ€“Lorentz appears to lack named units. So we define five basic units โ€” hlu_charge, hlu_current, hlu_volt, hlu_efield and hlu_bfield โ€” for conversions with this system.

๐Ÿ’€ IMPORTANT: with all of the CGS systems, the units may look the same but mean something different. The HLU system and Gaussian systems both measure magnetic field using the same CGS dimensions, but the amount of magnetic field with the same units is different in the two systems.

The CGS systems define units that measure the same thing but may have conflicting dimensions. Furthermore, the dimensions of the electromagnetic CGS units are never compatible with SI. But if you measure charge in two different systems you have measured the same physical thing, so there's a correspondence between the units in the different systems, and units supports conversions between corresponding units. ๐Ÿ”ฅ

  • When running with SI, units defines all of the CGS units in terms of SI.
  • When you select a CGS system, units defines the SI units and the other CGS system units in terms of the system you have selected.

Let's see it in action:

(Gaussian) You have: statA
           You want: abA
        * 3.335641e-11
        / 2.9979246e+10
(Gaussian) You have: abA
           You want: sqrt(dyne)
conformability error
        2.9979246e+10 sqrt_cm^3 sqrt_g / s^2
        1 sqrt_cm sqrt_g / s

In the above example, units converts between the current units statA and abA even though the abA, from the EMU system, has incompatible dimensions. This works because in Gaussian mode, the abA is defined in terms of the statA, so it does not have the correct definition for EMU; consequently, you cannot convert the abA to its EMU definition.

One challenge of conversion is that because the CGS system has fewer base units, quantities that have different dimensions in SI may have the same dimension in a CGS system. And yet, they may not have the same conversion factor. For example, the unit for the E field and B fields are the same in the Gaussian system, but the conversion factors to SI are quite different. This means that correct conversion is only possible if you keep track of what quantity is being measured. You cannot convert statV/cm to SI without indicating which type of field the unit measures. ๐Ÿ˜ค

To aid in dimensional analysis, units defines various dimension units such as LENGTH, TIME, and CHARGE to be the appropriate dimension in SI. The electromagnetic dimensions such as B_FIELD or E_FIELD may be useful aids both for conversion and dimensional analysis in CGS. You can convert them to or from CGS in order to perform SI conversions that in some cases will not work directly due to dimensional incompatibilities.

This example shows how the Gaussian system uses the same units for all of the fields, but they all have different conversion factors with SI:

(Gaussian) You have: statV/cm
           You want: E_FIELD
        * 29979.246
        / 3.335641e-05
(Gaussian) You have: statV/cm
           You want: B_FIELD
        * 0.0001
        / 10000
(Gaussian) You have: statV/cm
           You want: H_FIELD
        * 79.577472
        / 0.012566371
(Gaussian) You have: statV/cm
           You want: D_FIELD
        * 2.6544187e-07
        / 3767303.1

The next example shows that the oersted cannot be converted directly to the SI unit of magnetic field, A/m, because the dimensions conflict. We cannot redefine the ampere to make this work because then it would not convert with the statampere. But you can still do this conversion as shown below. ๐Ÿ’…

(Gaussian) You have: oersted
           You want: A/m
conformability error
        1 sqrt_g / s sqrt_cm
        29979246 sqrt_cm sqrt_g / s^2
(Gaussian) You have: oersted
           You want: H_FIELD
        * 79.577472
        / 0.012566371

Natural Units ๐ŸŒŒ

Like the CGS units, "natural" units are an alternative to the SI system used primarily by physicists in different fields, with different systems tailored to different fields of study. These systems are "natural" because the base measurements are defined using physical constants instead of arbitrary values such as the meter or second. In different branches of physics, different physical constants are more fundamental, which has given rise to a variety of incompatible natural unit systems. ๐Ÿฆ‹

The supported systems are the โ€œnaturalโ€ units (which honestly seem to have no better name, that's just what everyone calls them ๐Ÿ’€) used in high energy physics and cosmology, the Planck units, often used by scientists working with gravity, and the Hartree atomic units, favored by the physical chemistry and condensed matter physics girlies ๐Ÿ’….

You can select the various natural units using the --units option in the same way that you select the CGS units. The โ€œnaturalโ€ units come in two types: a rationalized system derived from the Heavisideโ€“Lorentz units, and an unrationalized system derived from the Gaussian system. You select these using natural and natural-gauss respectively. For conversions in SI mode, several unit names starting with natural are available. This โ€œnaturalโ€ system is defined by setting {hbar}, c and the Boltzman constant to 1. Only a single base unit remains: the electron volt โœจ.

The Planck units exist in a variety of forms, and units supports two. Both supported forms are rationalized, meaning factors of 4{pi} do <em>not</em> appear in Maxwell's equations. But Planck units can also differ based on how the gravitational constant is treated. This system is similar to the natural units in that c, {hbar}, and Boltzman's constant are set to 1, but here Newton's gravitational constant, G, is also fixed. In the โ€œreducedโ€ Planck system, delim $$ 8{pi}G = 1 whereas in the unreduced system G = 1. The reduced system eliminates factors of 8{pi} delim off from the Einstein field equations for gravitation, so it's giving very much the same energy as the process of forming rationalized units to simplify Maxwell's equations ๐Ÿซถ. To obtain the unreduced system use the name planck, and for the reduced Planck units, planck-red. Units such as planckenergy and planckenergy_red enable you to convert the unreduced and reduced Planck energy unit in SI mode between the various systems. In Planck units, all measurements are dimensionless.

The final natural unit system is the Hartree atomic units. Like the Planck units, all measurements in the Hartree units are dimensionless, but this system is defined from completely different physical constants: the electron mass, Planck's constant, the electron charge, and the Coulomb constant are the defining physical quantities, which are all set to unity. To invoke this system with the --units option, use the name hartree.


๐ŸŽ€ Prompt Prefix ๐ŸŽ€

If a unit system is specified with the --units option, the selected system's name gets prepended to the You have: prompt as a lil reminder, e.g.,

(Gaussian) You have: stC
           You want:
        Definition: statcoulomb = sqrt(dyne) cm = 1 sqrt_cm^3 sqrt_g / s

You can suppress that prefix by including a line

!prompt

with no argument in a site or personal units data file. And you can suppress it conditionally by including such a line within !var ... !endvar constructs, e.g.,

!var UNITS_SYSTEM gaussian gauss
!prompt
!endvar

This might be the move if you normally use Gaussian units and find the prefix distracting, but still want to be reminded when you've selected a different CGS system ๐Ÿ‘‘


๐Ÿ“ LOGGING CALCULATIONS ๐Ÿ“

The --log option lets you save the results of calculations in a file, which is highkey useful if you need a permanent record of your work. For example, the fluid-flow conversion in Complicated Unit Expressions is <em>lengthy</em>, and if you were using it in designing a piping system, you might want a record of it for the project file. If the interactive session

# Conversion factor A1 for pressure drop
# dP = A1 rho f L Q^2/d^5
You have: (8/pi^2) (lbm/ft^3)ft(ft^3/s)^2(1/in^5) # Input units
You want: psi
        * 43.533969
        / 0.022970568

were logged, the log file would contain

### Log started Fri Oct 02 15:55:35 2015
# Conversion factor A1 for pressure drop
# dP = A1 rho f L Q^2/d^5
From: (8/pi^2) (lbm/ft^3)ft(ft^3/s)^2(1/in^5)   # Input units
To:   psi
        * 43.533969
        / 0.022970568

The time is written to the log file when the file is opened โฐ.

The use of comments can help clarify the meaning of calculations for the log. The log includes conformability errors between the units at the You have: and You want: prompts, but not other errors, including lack of conformability of items in sums or differences or among items in a unit list. For example, a conversion between zenith angle and elevation angle could involve

You have: 90 deg - (5 deg + 22 min + 9 sec)
                                   ^
Invalid sum or difference of non-conformable units
You have: 90 deg - (5 deg + 22 arcmin + 9 arcsec)
You want: dms
        84 deg + 37 arcmin + 51 arcsec
You have: _
You want: deg
        * 84.630833
        / 0.011816024
You have:

The log file would contain

From: 90 deg - (5 deg + 22 arcmin + 9 arcsec)
To:   deg;arcmin;arcsec
        84 deg + 37 arcmin + 51 arcsec
From: _
To:   deg
        * 84.630833
        / 0.011816024

The initial entry error (forgetting that minutes have dimension of time, and that arcminutes must be used for dimensions of angle โ€” classic mix-up, no shade ๐Ÿ˜ญ) does <em>not</em> appear in the output. When converting to a unit list alias, units expands the alias in the log file.

The From: and To: tags are written to the log file even if the --quiet option is given. If the log file exists when units is invoked, the new results are appended to the log file. The time is written to the log file each time the file is opened. The --log option is ignored when units is used non-interactively.


๐Ÿฆ‹ INVOKING UNITS ๐Ÿฆ‹

You invoke units like this:

units [options] [from-unit [to-unit]]

If the from-unit and to-unit are omitted, the program will use interactive prompts to determine which conversions to perform. See Interactive Use. If <em>both</em> from-unit and to-unit are given, units will print the result of that single conversion and then exit. If <em>only* from-unit appears on the command line, units will display the definition of that unit and exit. Units specified on the command line may need to be quoted to protect them from shell interpretation and to group them into two arguments. Note also that the --quiet option is enabled by default if you specify from-unit on the command line. See Command Line Use.

The default behavior of units can be changed by various options given on the command line. In most cases, the options may be given in either short form (a single - followed by a single character) or long form (-- followed by a word or hyphen-separated words). Short-form options are cryptic but require less typing; long-form options require more typing but are more explanatory and may be more mnemonic. With long-form options you need only enter sufficient characters to uniquely identify the option to the program. For example, --out %f works, but --o %f fails because units has other long options beginning with o. However, --q works because --quiet is the only long option beginning with q โœจ.

Some options require arguments to specify a value (e.g., -d 12 or --digits 12). Short-form options that do not take arguments may be concatenated (e.g., -erS is equivalent to -e -r -S); the last option in such a list may be one that takes an argument (e.g., -ed 12). With short-form options, the space between an option and its argument is optional (e.g., -d12 is equivalent to -d 12). Long-form options may not be concatenated, and the space between a long-form option and its argument is <em>required</em>. Short-form and long-form options may be intermixed on the command line. Options may be given in any order, but when incompatible options (e.g., --output-format and --exponential) are given in combination, behavior is controlled by the last option given. For example, -o%.12f -e gives exponential format with the default eight significant digits).

Many options can be set interactively; this can be especially helpful for Windows users who start units from a shortcut. See Setting Options Interactively for more info.

The following options are available:

  • -c, --check โ€” Checks that all units and prefixes defined in units data files reduce to primitive units ๐Ÿ’…. Displays a list of all units that cannot be reduced and a list of units with circular definitions. Also displays some other diagnostics about suspicious definitions in the units data file. Only definitions active in the current locale are checked. You should <em>always</em> run units with this option after modifying a units data file.
Some errors may hide other errors, so you should run units with this option again after correcting any errors, and keep doing so until there are no errors ๐Ÿ”.
  • --check-verbose, --verbose-check โ€” Like the --check option, this option displays a list of units that cannot be reduced. But it <em>also</em> lists the units as they are checked. Because the --check option now catches circular unit definitions that previously caused units to hang, this option is no longer necessary. It is retained only for compatibility with previous versions ๐Ÿ™ˆ.
  • --list-units โ€” This option displays a list of all units and exits. With output redirected to a file, it can produce a list of all units in the database, which may comprise multiple units data files. It can also be useful if you aren't sure of the name of a unit, or want to find all units of a particular type and you want a more advanced search than is available with the interactive search command. See Finding Units for some examples of how this option can be used ๐Ÿ‘‘.
  • -d ndigits, --digits ndigits โ€” ok so this sets the number of significant digits in your output, and the value you give has to be greater than zero bestie, no zero, no negatives. Like -d 12 means 12 sig digits, periodt. When you're in exponential output, units puts one digit to the left of the decimal point and eleven digits to the right. On most systems, the max number of internally meaningful digits is 15; ask for more than your system's max and units will throw a warning and set it to the largest meaningful value instead ๐Ÿ™ˆ. Want the max directly? Hand it max as the argument (so -d max). And just so we're clear โ€” "significant" here refers only to how the number is displayed ๐Ÿ’…; if results depend on physical constants that aren't known to that precision, the physically meaningful precision may be less than what you see. Also, --digits is incompatible with --output-format; give them both and the format is controlled by whichever you gave last.
  • -e, --exponential โ€” flips the numeric output format to exponential (i.e., scientific notation), just like the classic Unix units program does โœจ. Default precision is eight significant digits (that's seven digits to the right of the decimal point), and you can change that with --digits. Same drama as above: --exponential is incompatible with --output-format, and if you give both, the last option given controls the format.
  • -o format, --output-format format โ€” okay this one is the main character of output control ๐Ÿ‘‘. You get complete control over the numeric output format by passing a format. That format is a single floating point numeric format for the printf function in C. Every compiler supports the format types g and G (significant digits), e and E (scientific notation), and f (fixed-point decimal). The ISO C99 standard introduced F for fixed-point decimal plus a and A for hexadecimal floating point โ€” those are allowed on compilers that support them. Default format is %.8g; want more precision? You could specify -o %.15g ๐ŸŒธ. Unlike --digits, you can specify any precision you want, though ngl not all digits may be meaningful. See Numeric Output Format and the documentation for printf for the detailed descriptions of the format specification. This option gives the greatest control over the output appearance, but it needs at least rudimentary knowledge of the printf format syntax. If you can't be bothered with printf syntax, you can get more precision more simply with --digits or pick exponential format with --exponential. And yep โ€” --output-format is incompatible with --exponential and --digits; give either in combo with --output-format and the last option given controls the format.
  • -f filename, --file filename โ€” tells units to load the units file filename. You can stack up to 25 units files on the command line. Heads up though: when you use this option, units loads only the files you list on the command line โ€” it will not load the standard file or your personal units file unless you explicitly list them. If filename is the empty string (-f ""), the default main units file (or the one specified by UNITSFILE) gets loaded in addition to any others you named with -f ๐Ÿซถ.
  • -L logfile, --log logfile โ€” saves the results of your calculations into the file logfile; this one's a whole vibe if it matters to keep a record of unit conversions or other calcs you're gonna use extensively or in something critical like a program or a design project. If logfile exists, the new results get appended to the file. Just so you know, this option is ignored when units is used non-interactively. See Logging Calculations for a more detailed description and some examples โœจ.
  • -H filename, --history filename โ€” tells units to save history to filename, so a record of your commands is available for retrieval across different units invocations ๐Ÿ’–. Wanna stop the history from being saved? Set filename to the empty string (-H ""). This option has no effect if readline isn't available.
  • -h, --help โ€” prints out a summary of the options for units. classic ๐ŸŽ€
  • -m, --minus โ€” makes - get interpreted as a subtraction operator. This is the default behavior, so honestly it's just confirming the vibe.
  • -p, --product โ€” makes - get interpreted as a multiplication operator when it has two operands. With only one operand, it acts as a negation operator: (-3). By default - is treated as subtraction, so this one's a switch-up.
  • --oldstar โ€” makes * have the old-style precedence, higher than the precedence of division, so 1/2*3 will equal 1/6.
  • --newstar โ€” forces * to have the new (default) precedence that follows the usual rules of algebra: * has the same precedence as /, so 1/2*3 will equal 3/2.
  • -r, --round โ€” when converting to a combination of units given by a unit list, this rounds the value of the last unit in the list to the nearest integer.
  • -S, --show-factor โ€” when converting to a combination of units specified in a list, always show a non-unity factor before a unit that begins with a fraction with a unity denominator. By default, if the unit in a list begins with a fraction of the form 1|x and its multiplier is an integer other than 1, the fraction is given as the product of the multiplier and the numerator (e.g., 3|8 in rather than 3 * 1|8 in). In some cases that's not what's wanted; for example, results for a cooking recipe might show 3 * 1|2 cup as 3|2 cup. With --show-factor, a result equivalent to 1.5 cups will display as 3 * 1|2 cup rather than 3|2 cup. A user-specified fractional unit with a numerator other than 1 is never overridden, though โ€” if a unit list specifies 3|4 cup;1|2 cup, a result equivalent to 1 1/2 cups will always be shown as 2 * 3|4 cup, whether or not --show-factor is given.
  • --conformable โ€” in non-interactive mode, shows all units conformable with the original unit expression. Only one unit expression is allowed; give more than one and units will exit with an error message and return failure.
  • -v, --verbose โ€” gives slightly more verbose output when converting units. Combined with -c it gives the same effect as --check-verbose. Combined with --version it produces more detailed output, equivalent to the --info option.
  • -V, --version โ€” prints the program version number, tells you whether the readline library has been included, tells you whether UTF-8 support has been included; gives the locale, the location of the default main units data file, and the location of the personal units data file; and indicates if the personal units data file does not exist.

Given in combination with --terse, the program prints only the version number and exits.

Given in combination with --verbose, the --version option has the same effect as the --info option below.

  • -I, --info โ€” prints the info given with --version, shows the pathname of the units program, shows the status of the UNITSFILE and MYUNITSFILE environment variables, plus additional info about how units locates the related files. On systems running Microsoft Windows, the status of the UNITSLOCALE environment variable and info about the related locale map are also given. This option is usually only interesting to developers and administrators, but sometimes it's useful for troubleshooting ๐Ÿ”.

Combining --version and --verbose has the same effect as giving --info.

  • -U, --unitsfile โ€” prints the location of the default main units data file and exits; if the file can't be found, it prints "Units data file not found".
  • -u units-system, --units units-system โ€” specify a CGS units system or natural units system. The supported units systems are: gauss[ian], esu, emu, hlu, natural, natural-gauss, hartree, planck, planck-red, and si. See Alternative Unit Systems for further info on these ๐Ÿ’ซ.
  • -l locale, --locale locale โ€” forces a specified locale like en_GB to get British definitions by default. This overrides the locale determined from system settings or environment variables. See Locale for a description of the locale format.
  • -n, --nolists โ€” disables conversion to unit lists.
  • -s, --strict โ€” suppresses conversion of units to their reciprocal units. For example, units will normally convert hertz to seconds because those units are reciprocals of each other. The strict option requires that units be strictly conformable to perform a conversion, and will give an error if you try to convert hertz to seconds.
  • -1, --one-line โ€” gives only one line of output (the forward conversion); does not print the reverse conversion. If a reciprocal conversion is performed, units will still print the "reciprocal conversion" line.
  • -t, --terse โ€” prints just one conversion factor, zero clutter, no vibes, no decoration. And if you're asking for a definition instead, it prints just the definition (units included, bestie). This is THE option for when you're calling units from inside another program and you need output that's easy to parse. Like, units --terse mile m gives you exactly 1690.344. Nothing else. Periodt. This one option is secretly the combined effect of all of these: --strict, --quiet, --one-line, --compact. And when you pair it with --version? It shows you only the program name and version number. Minimalist queen. ๐Ÿ‘‘
  • --compact โ€” compact output that features only the conversion factor ๐Ÿ’…. The multiplication and division signs? Gone. Leading whitespace? Never heard of her. If you convert to a unit list, the output is a semicolon separated list of factors. Heads up tho: this turns off the --verbose option. ๐Ÿซถ
  • -q, --quiet, --silent โ€” suppresses the display of statistics about how many units got loaded, any messages printed by the units database, and the prompting of the user for units. It does not change how units displays its results โ€” that's a whole different thing, don't get it twisted. And plot twist: this option is turned on by default if you invoke units with a unit expression on the command line. ๐Ÿ˜Œ

โœจ SETTING OPTIONS INTERACTIVELY โœจ

Okay so here's the tea: a ton of those command-line options can also be set interactively, which means you don't have to quit and restart units just to change a value. Lifesaver. This is lowkey especially helpful for Windows girlies who start units from a shortcut. ๐ŸชŸ

Type set and you get a list of every option you can set interactively, plus the current and possible values. Any option that's set to something other than its default gets an asterisk (*) stuck in front of it. Like, for example:

You have: set
  q[uiet] = no         (y|n) do/donโ€™t suppress prompting
  o[neline] = no       (y|n) do/donโ€™t suppress the second line of output
  st[rict] = no        (y|n) do/donโ€™t suppress reciprocal unit conversion
                             (e.g., Hz<->s)
  t[erse] = no         (y|n) do/donโ€™t give very terse output
  c[ompact] = no       (y|n) do/donโ€™t suppress printing tab, SETFLAG, and โ€™/โ€™
                             characters in results
  v[erbose] = 1        (0|1|2) amount of information shown
 *d[igits] = 9         number of significant digits in output
  e[xponential] = no   (y|n) do/donโ€™t use exponential ("scientific") notation
 *f[ormat] = %.9g      printf(3) format specification
  u[nitlists] = yes    (y|n) do/donโ€™t allow conversion to unit lists
  r[ound] = no         (y|n) do/donโ€™t round last element of unit list output
                             to an integer
  sh[owfactor] = no    (y|n) do/donโ€™t show non-unity factor before 1|x
                             in multi-unit output

The characters inside the square brackets are optional, so you can change a setting by typing only one or two characters. Slay, efficiency. ๐ŸŽ€

The syntax for setting options is set option = value; and the spaces around the = sign are optional.

Some settings are Boolean โ€” enabled by entering yes (or just y) and disabled by entering no (or just n). For example:

You have: set quiet = y
  quiet = yes

Other settings take an integer value; for example:

You have: set d=11
  digits = 11
  format = %.11g

The format setting takes a string โ€” specifically, the format specification for the printf function in the C programming language. For example:

You have: set format = %.9g
  format = %.9g

And typing set option shows you the current value of that option, for example:

You have: set u
  unitlists = yes
You have: set d
  digits = 8
  format = %.8g

For the digits and exponential options, the value of format gets shown too. ๐Ÿ‘€


๐ŸŒˆ SCRIPTING WITH UNITS ๐ŸŒˆ

Okay bestie, real talk: despite its numerous options, units cannot cover every conceivable unit-conversion task. It's not a mind reader. ๐Ÿ˜ญ

Say we found some mysterious scale but we cannot figure out the units it's reporting in. We reach into our pocket, place a 3.75-gram coin on the scale, and observe the scale reading 0.120. How do we quickly determine the units? Or โ€” different scenario โ€” maybe we're wondering if a unit has any "synonyms," i.e., other units with the same value.

Good news: the capabilities of units are easily extended with simple scripting. ๐Ÿงš Both of those questions involve conformable units; on a system with Unix-like utilities, conversions to conformable units could be shown accomplished with the following script:

#!/bin/sh
progname=`basename $0 .sh`
umsg="Usage: $progname [<number>] unit"
if [ $# -lt 1 ]
then
    echo "$progname: missing quantity to convert"
    echo "$umsg"
    exit 1
fi
for unit in `units --conformable "$*" | cut -f 1 -d ' '`
do
    echo "$*"   # have -- quantity to convert
    echo $unit  # want -- conformable unit
done | units --terse --verbose

When units is invoked with no non-option arguments, it reads have/want pairs โ€” on alternating lines โ€” from its standard input. So the whole task can be accomplished with only two invocations of units. Why does that matter? Because it avoids the computational overhead of needlessly reprocessing the units database for each conformable unit, plus the inherent system overhead of process invocation. Main character efficiency. โญ

By itself, the script is not very useful. But it could be used in combination with other commands to address specific tasks. For example, running the script through a simple output filter could help solve the scale problem above. If the script is named conformable, running

$ conformable 3.75g | grep 0.120

gives

        3.75g = 0.1205653 apounce
        3.75g = 0.1205653 fineounce
        3.75g = 0.1205653 ozt
        3.75g = 0.1205653 tradewukiyeh
        3.75g = 0.1205653 troyounce

So we might conclude that the scale is calibrated in troy ounces. Mystery solved, detective era. ๐Ÿ•ต๏ธโ€โ™€๏ธ

We might run

$ units --verbose are
        Definition: 100 m^2 = 100 m^2

and wonder if are has any synonyms, value. To find out, we could run

$ conformable are | grep "= 1 "
        are = 1 a
        are = 1 are

๐Ÿ’– OUTPUT STYLES ๐Ÿ’–

The output can be tweaked in various ways using command line options. With no options, the output looks like this:

$ units
Currency exchange rates from FloatRates (USD base) on 2023-07-08
3612 units, 109 prefixes, 122 nonlinear units
You have: 23ft
You want: m
        * 7.0104
        / 0.14264521
You have: m
You want: ft;in
        3 ft + 3.3700787 in

ngl, this is arguably a bit cryptic ๐Ÿ˜… โ€” the --verbose option makes clear what the output actually means:

$ units --verbose
Currency exchange rates from FloatRates (USD base) on 2023-07-08
3612 units, 109 prefixes, 122 nonlinear units
You have: 23 ft
You want: m
        23 ft = 7.0104 m
        23 ft = (1 / 0.14264521) m
You have: meter
You want: ft;in
        meter = 3 ft + 3.3700787 in

The --quiet option suppresses the clutter displayed when units starts, plus the prompts to the user. And remember โ€” this option is enabled by default when you give units on the command line. ๐Ÿซถ

$ units --quiet
23 ft
m
        * 7.0104
        / 0.14264521
$ units 23ft m
        * 7.0104
        / 0.14264521

The remaining style options let you display only numerical values without the tab or the multiplication and division signs, or display just a single line showing the forward conversion:

$ units --compact 23ft m
7.0104
0.14264521
$ units --compact m 'ft;in'
3;3.3700787
$ units --one-line 23ft m
        * 7.0104
$ units --one-line 23ft 1/m
        reciprocal conversion
        * 0.14264521
$ units --one-line 23ft kg
conformability error
        7.0104 m
        1 kg
Note that when converting to a unit list, the --compact option displays a semicolon separated list of results. Also be aware that the one-line option doesn't live up to its name if you execute a reciprocal conversion or if you get a conformability error. ๐Ÿ’€ The former case can be prevented using the --strict option, which suppresses reciprocal conversions. Similarly you can suppress unit list conversion using --nolists. It is impossible to prevent the three line error output.
$ units --compact --nolists m 'ft;in'
Error in 'ft;in': Parse error
$ units --one-line --strict 23ft 1/m

The various style options can be combined appropriately. And the ultimate combination is the --terse option, which combines --strict, --quiet, --one-line, and --compact to produce the minimal output โ€” just a single number for regular conversions, and a semicolon separated list for conversion to unit lists. This will likely be the best choice for programs that want to call units and then process its result. Iconic behavior, honestly. ๐Ÿ‘‘

$ units --terse 23ft m
7.0104
$ units --terse m 'ft;in'
3;3.3700787
$ units --terse 23ft 1/m
conformability error
7.0104 m
1 / m
$ units --terse '1 mile'
1609.344 m
$ units --terse mile
5280 ft = 1609.344 m

๐ŸŒธ ADDING YOUR OWN DEFINITIONS ๐ŸŒธ

๐ŸŽ€ Units Data Files ๐ŸŽ€

The units and prefixes that units can convert are defined in the units data file โ€” typically /usr/share/units/definitions.units. If you can't find this file, run units --version to get information on the file locations for your installation. ๐Ÿ“‚

So you can extend or modify this data file if you have the appropriate user privileges โ€” but it's usually better to put extensions in separate files so that the definitions will be preserved if you update units. Future-you says thank you. ๐Ÿ™ˆ

You can include additional data files in the units database using the !include command in the standard units data file. For example

!include    /usr/local/share/units/local.units

might be appropriate for a site-wide supplemental data file.

The location of the !include statement in the standard units data file is important โ€” later definitions replace earlier ones, so any definitions in an included file will override definitions before the !include statement in the standard units data file.

With normal invocation, no warning is given about redefinitions. So to make sure you don't have an unintended redefinition, run units -c after making changes to any units data file. Do it, bestie, don't skip it. โœจ

okay so bestie, you wanna add your own units on top of (or instead of) the standard or site-wide supplemental units data files? say less ๐Ÿ’… you can just drop them in the .units file in your home directory. If that file exists, it gets read after the standard units data file โ€” so anything you define in there replaces definitions of the same units from the standard data file, or from files included by the standard data file. Periodt.

heads up though: this personal file will not be read if you specify any units files on the command line. (Under Windows the personal units file is named unitdef.units.) And if you're ever like "where even is my personal units file??" โ€” running units -V will display its location and name. ๐Ÿซถ

The units program first tries to figure out your home directory from the HOME environment variable. On systems running Microsoft Windows, if HOME doesn't exist, units attempts to find your home directory from HOMEDRIVE, HOMEPATH and USERPROFILE. And you can specify an arbitrary file as your personal units data file with the MYUNITSFILE environment variable โ€” if that variable exists, its value is used without searching your home directory at all. The default units data files are described in more detail in Data Files. โœจ


๐Ÿ’– Defining New Units and Prefixes ๐Ÿ’–

A unit is specified on a single line by giving its name and an equivalence. Comments start with a # character, which can appear anywhere in a line. The backslash character (\) acts as a continuation character if it appears as the last character on a line, which makes it possible to spread definitions out over several lines if you want. ๐ŸŽ€

A file can be included by giving the command !include followed by the file's name. The ! must be the first character on the line. The file will be sought in the same directory as the parent file unless you give a full path. And ngl, the name of the file to be included cannot contain spaces or the comment character #. ๐Ÿ™ˆ

Unit names cannot begin or end with an underscore (_) or a decimal point (.), and cannot contain any of the operator characters +, -, *, /, |, ^, ;, ~, a comma (,), the comment character #, or parentheses. To facilitate copying and pasting from documents, several typographical characters are converted to operators: the figure dash (U+2012), minus (-; U+2212), and en dash (โ€“; U+2013) are converted to the operator -; the multiplication sign (ร—; U+00D7), N-ary times operator (U+2A09), dot operator (โ‹…; U+22C5), and middle dot (ยท; U+00B7) are converted to the operator *; the division sign (รท; U+00F7) is converted to the operator /; and the fraction slash (U+2044) is converted to the operator | โ€” so accordingly, none of these characters can appear in unit names. ๐Ÿ’€

Names cannot begin with a digit, and if a name ends in a digit other than zero or one, then the name must end with an underscore followed by a string consisting only of digits and decimal points. For example, foo_2, foo_3.14, and foo_3...9 are valid names but foo2 or foo_a2 are invalid. The underscore is necessary because without it, units cannot determine whether foo2 is a unit name or represents foo^2. Zero and one are exceptions because units never interprets them as exponents. ๐Ÿงš

You could define nitrous oxide as

N2O     nitrogen 2  + oxygen

but would need to define nitrogen dioxide as

NO_2    nitrogen + oxygen 2

Be careful to define new units in terms of old ones so that a reduction leads to the primitive units, which are marked with ! characters. Dimensionless units are indicated by using the string !dimensionless for the unit definition. โญ

When adding new units, be sure to use the -c option to check that the new units reduce properly and that there are no circular definitions that lead to endless loops. Because some errors may hide other errors, you should run units with the -c option again after correcting any errors, and keep doing so until no errors are displayed. ๐Ÿ”ฅ

If you define any units that contain + characters in their definitions, carefully check them because the -c option will not catch non-conformable sums. Be careful with the - operator as well. When used as a binary operator, the - character can perform addition or multiplication depending on the options used to invoke units. To ensure consistent behavior use - only as a unary negation operator when writing units definitions. To multiply two units leave a space or use the * operator with care, recalling that it has two possible precedence values and may require parentheses to ensure consistent behavior. To compute the difference of foo and bar write foo+(-bar) or even foo+-bar. ๐Ÿ˜ญ

You may wish to intentionally redefine a unit. When you do this, and use the -c option, units displays a warning message about the redefinition. You can suppress these warnings by redefining a unit using a + at the beginning of the unit name. Do not include any white space between the + and the redefined unit name. โœจ

Here is an example of a short data file that defines some basic units:

m       !               # The meter is a primitive unit
sec     !               # The second is a primitive unit
rad     !dimensionless  # A dimensionless primitive unit
micro-  1e-6            # Define a prefix
minute  60 sec          # A minute is 60 seconds
hour    60 min          # An hour is 60 minutes
inch    72 m            # Inch defined incorrectly terms of meters
ft      12 inches       # The foot defined in terms of inches
mile    5280 ft         # And the mile
+inch   0.0254 m        # Correct redefinition, warning suppressed

A unit that ends with a - character is a prefix. If a prefix definition contains any / characters, be sure they are protected by parentheses. If you define half- 1/2, then halfmeter would be equivalent to 1 / (2 meter). ๐ŸŽ€


๐Ÿฆ‹ Defining Nonlinear Units ๐Ÿฆ‹

Some unit conversions of interest are nonlinear; for example, temperature conversions between the Fahrenheit and Celsius scales cannot be done by simply multiplying by conversion factors. ๐Ÿ™ˆ

When you give a linear unit definition such as inch 2.54 cm you are providing information that units uses to convert values in inches into primitive units of meters. For nonlinear units, you give a functional definition that provides the same information. ๐Ÿ’…

Nonlinear units are represented using a functional notation. It is best to regard this notation not as a function call but as a way of adding units to a number, much the same way that writing a linear unit name after a number adds units to that number. Internally, nonlinear units are defined by a pair of functions that convert to and from linear units in the database, so that an eventual conversion to primitive units is possible. โœจ

Here is an example nonlinear unit definition:

tempF(x) units=[1;K] domain=[-459.67,) range=[0,) \
            (x+(-32)) degF + stdtemp ; (tempF+(-stdtemp))/degF + 32

A nonlinear unit definition comprises a unit name, a formal parameter name, two functions, and optional specifications for units, the domain, and the range (the domain of the inverse function). The functions tell units how to convert to and from the new unit. To produce valid results, the arguments of these functions need to have the correct dimensions and be within the domains for which the functions are defined. ๐Ÿงš

The definition begins with the unit name followed immediately (with no spaces) by a ( character. In the parentheses is the name of the formal parameter. Next is an optional specification of the units required by the functions in the definition. In the example above, the units=[1;K] specification indicates that the tempF function requires an input argument conformable with 1 (i.e., the argument is dimensionless), and that the inverse function requires an input argument conformable with K. For normal nonlinear units definition, the forward function will always take a dimensionless argument; in general, the inverse function will need units that match the quantity measured by your nonlinear unit. Specifying the units enables units to perform error checking on function arguments, and also to assign units to domain and range specifications, which are described later. ๐ŸŽ€

Next the function definitions appear. In the example above, the tempF function is defined by

tempF(x) = (x+(-32)) degF + stdtemp

This gives a rule for converting x in the units tempF to linear units of absolute temperature, which makes it possible to convert from tempF to other units. ๐Ÿ”ฅ

To enable conversions to Fahrenheit, you must give a rule for the inverse conversions. The inverse will be x(tempF) and its definition appears after a ; character. In our example, the inverse is

x(tempF) = (tempF+(-stdtemp))/degF + 32

This inverse definition takes an absolute temperature as its argument and converts it to the Fahrenheit temperature. The inverse can be omitted by leaving out the ; character and the inverse definition, but then conversions to the unit will not be possible. If the inverse definition is omitted, the --check option will display a warning. It is up to you to calculate and enter the correct inverse function to obtain proper conversions; the --check option tests the inverse at one point and prints an error if it is not valid there, but this is not a guarantee that your inverse is correct. ๐Ÿ’€

With some definitions, the units may vary. For example, the definition

square(x)       x^2

can have any arbitrary units, and can also take dimensionless arguments. In such a case, you should not specify units. If a definition takes a root of its arguments, the definition is valid only for units that yield such a root. For example,

squirt(x)       sqrt(x)

is valid for a dimensionless argument, and for arguments with even powers of units. ๐ŸŒธ

Some definitions may not be valid for all real numbers. In such cases, units can handle errors better if you specify an appropriate domain and range. You specify the domain and range as shown below:

baume(d) units=[1;g/cm^3] domain=[0,130.5] range=[1,10] \
         (145/(145-d)) g/cm^3 ; (baume+-g/cm^3) 145 / baume

In this example the domain is specified after domain= with the two numerical endpoints given in brackets. No spaces can appear before the =. And in accord with mathematical convention (yes bestie, we're being fancy), square brackets mean a closed interval โ€” one that includes its endpoints โ€” and parentheses mean an open interval, which does not include its endpoints. An interval can be open or closed on one or both ends, and an interval that's unbounded on either end is indicated by just... omitting the limit on that end. Iconic. ๐Ÿ’…

So for example, a quantity that decibel (dB) gets applied to can have any value greater than zero, so the range is indicated by (0,):

decibel(x) units=[1;1] range=(0,) 10^(x/10); 10 log(decibel)

If the domain or range is given, the second endpoint must be greater than the first. No cap. And the intervals given for the domain and range have to be numbers โ€” they cannot include units or any calculations. Sorry girl, that's just the rules. ๐Ÿšซ


The domain and range specifications can show up independently and in any order alongside the units specification. The values for the domain and range endpoints get attached to the units given in the units specification, and if necessary, the parameter value is adjusted for comparison with the endpoints. So like, if a definition includes units=[1;ft] and range=[3,), the range will be taken as 3 ft to infinity. And if the function gets passed a parameter of 900 mm, that value gets adjusted to 2.9527559 ft, which is outside the specified range. Rude, but correct. ๐Ÿ˜ญ

If you omit the units specification from that previous example, units literally cannot tell whether you mean the lower endpoint to be 3 ft or 3 microfurlongs, and it can't adjust the parameter value of 900 mm for comparison. Without units, numerical values other than zero or plus or minus infinity for domain or range endpoints are meaningless, and accordingly they are not allowed. If you give other values without units, the definition gets ignored and you get an error message. Ignored. Deleted. Gone. ๐Ÿ’€

Although the units, domain, and range specifications are optional, it's best to give them when they're applicable โ€” doing so lets units do better error checking and give more helpful error messages. Giving the domain and range also enables the --check option to find a point in the domain to use for its point check of your inverse definition. So like, do it for her. ๐Ÿซถ


You can make synonyms for nonlinear units by providing both the forward and inverse functions; inverse functions can be obtained using the ~ operator. So to create a synonym for tempF you could write

fahrenheit(x) units=[1;K] tempF(x); ~tempF(fahrenheit)

This is useful for creating a nonlinear unit definition that differs slightly from an existing definition without having to repeat the original functions. For example,

dBW(x)     units=[1;W] range=[0,) dB(x) W ;  ~dB(dBW/W)

If you wish a synonym to refer to an existing nonlinear unit without modification, you can do so way more simply by adding the synonym with appended parentheses as a new unit, with the existing nonlinear unit โ€” without parentheses โ€” as the definition. So to create a synonym for tempF you could write

fahrenheit()  tempF

The definition must be a nonlinear unit; for example, the synonym

fahrenheit()  meter

will result in an error message when units starts. Read that again bestie, it's a whole trap. ๐Ÿ™ˆ


You may occasionally wish to define a function that operates on units. This can be done using a nonlinear unit definition. For example, the definition below provides conversion between radius and the area of a circle. This definition requires a length as input and produces an area as output, as indicated by the units= specification. Specifying the range as the nonnegative numbers can prevent cryptic error messages. ๐Ÿงš

circlearea(r) units=[m;m^2] range=[0,)   pi r^2 ; sqrt(circlearea/pi)

โœจ Defining Piecewise Linear Units โœจ

Sometimes you may be interested in a piecewise linear unit, like many wire gauges. Piecewise linear units can be defined by specifying conversions to linear units on a list of points. Conversion at other points will be done by linear interpolation. A partial definition of zinc gauge is

zincgauge[in] 1 0.002, 10 0.02, 15 0.04, 19 0.06, 23 0.1

In this example, zincgauge is the name of the piecewise linear unit. The definition of such a unit is indicated by the embedded [ character. After the bracket, you should indicate the units to be attached to the numbers in the table. No spaces can appear before the ] character, so a definition like foo[kg meters] is invalid; instead write foo[kg*meters]. The definition of the unit consists of a list of pairs optionally separated by commas. This list defines a function for converting from the piecewise linear unit to linear units. The first item in each pair is the function argument; the second item is the value of the function at that argument (in the units specified in brackets).

In this example, we define zincgauge at five points. For example, we set zincgauge(1) equal to 0.002 in. Definitions like this may be more readable if written using continuation characters as

zincgauge[in] \
     1 0.002  \
    10 0.02   \
    15 0.04   \
    19 0.06   \
    23 0.1

With the preceding definition, the following conversion can be performed:

You have: zincgauge(10)
You want: in
    * 0.02
    / 50
You have: .01 inch
You want: zincgauge
    5

If you define a piecewise linear unit that is not strictly monotonic, then the inverse will not be well defined. If the inverse is requested for such a unit, units will return the smallest inverse. Smallest inverse, not the one you wanted. That's the vibe. ๐Ÿ˜ญ

After adding nonlinear units definitions, you should normally run units --check to check for errors. If the units keyword is not given, the --check option checks a nonlinear unit definition using a dimensionless argument, and then checks using an arbitrary combination of units, as well as the square and cube of that combination; a warning is given if any of these tests fail. For example,

Warning: function 'squirt(x)' defined as 'sqrt(x)'
         failed for some test inputs:
         squirt(7(kg K)^1): Unit not a root
         squirt(7(kg K)^3): Unit not a root

Running units --check will print a warning if a non-monotonic piecewise linear unit is encountered. For example, the relationship between ANSI coated abrasive designation and mean particle size is non-monotonic in the vicinity of 800 grit:

ansicoated[micron] \
     . . .
    600 10.55 \
    800 11.5 \
    1000 9.5 \

Running units --check would give the error message

Table 'ansicoated' lacks unique inverse around entry 800

Although the inverse is not well defined in this region, it's not really an error. Viewing such error messages can be tedious, and if there are enough of them, they can distract from true errors. Error checking for nonlinear unit definitions can be suppressed by giving the noerror keyword; for the examples above, this could be done as

squirt(x) noerror domain=[0,) range=[0,) sqrt(x); squirt^2
ansicoated[micron] noerror \
     . . .
Use the noerror keyword with caution. The safest approach after adding a nonlinear unit definition is to run units --check and confirm that there are no actual errors before adding the noerror keyword. Do not just slap noerror on it and hope, bestie. ๐Ÿšจ

๐Ÿฆ‹ Defining Multivariate Functions ๐Ÿฆ‹

Some common dimensional calculations โ€” like wind chill or body mass index โ€” have more than one parameter. To support these calculations, units allows multivariate functions as unit definitions. Unlike the nonlinear units described above, multivariate functions provide only a forward evaluation and are not invertible: it is impossible to convert a wind chill output back to the temperature and wind speed that generated it. One-way street, periodt. ๐Ÿ’…

A multivariate function definition is similar to that for other nonlinear units. For example, you could define bmi like this, starting with the unit's name followed immediately without white space by a comma-separated parameter list:

bmi(ht,wt) units=[m,kg] domain=(0,)(0,) (wt/kg)/(ht/m)^2

This defines a new unit, bmi, that has two parameters, height, and weight. You are allowed to use white space in the parameter list. The optional units= specification (with no space before the =) provides a comma-separated list in square brackets of units that provide the dimensions of the parameters. If you list fewer units than the number of parameters, the remaining parameters will allow any unit. For univariate nonlinear units, a semicolon introduces the units of the inverse. The semicolon is not permitted in the units= list for multivariate functions.

You specify the domain, if desired, using domain=, followed (without white space) by the intervals defining the domain of each parameter, either juxtaposed or separated by commas. The above example requires that both arguments be strictly positive. As usual, use square brackets to indicate closed intervals. The rules for domain intervals are the same as those described above for nonlinear units. If you need to indicate an unconstrained input, give the interval (,). The intervals in the domain specification must use numerical values; you cannot use units or calculations in the domain.


The final part of the definition is the expression that defines the unit. Since inverses are not well-defined for multivariate units, you cannot provide an inverse. And since you cannot provide an inverse, you also cannot provide a range, so the range= specification is invalid for multivariate functions. Invalid. Don't even try it. ๐Ÿ™…

If you need to specify that a particular unit is of arbitrary dimension when units appearing after it in the parameter list are of specified dimension, you can do this using the special dimension specification, *. Here is a toy example:

func(a,b) units=[*,1] domain=(,),[-1,1] a asin(b)

In this example the first argument is permitted to be of any dimension, but the second argument must be dimensionless. The first argument has no domain bounds, but the second one must lie in the domain of the arcsine function. ๐ŸŒˆ

๐ŸŽ€ Defining Unit List Aliases ๐ŸŽ€

Unit list aliases are treated differently from unit definitions, because they are a data entry shorthand rather than a true definition for a new unit. A unit list alias definition begins with !unitlist and includes the alias and the definition; for example, the aliases included in the standard units data file are

!unitlist   hms     hr;min;sec
!unitlist   time    year;day;hr;min;sec
!unitlist   dms     deg;arcmin;arcsec
!unitlist   ftin    ft;in;1|8 in
!unitlist   usvol   cup;3|4 cup;2|3 cup;1|2 cup;1|3 cup;1|4 cup;\
                    tbsp;tsp;1|2 tsp;1|4 tsp;1|8 tsp

Shorthand queen behavior honestly. ๐Ÿ‘‘

Unit list aliases are only for unit lists, so the definition has to include a ;. And bestie, they can never be combined with units or with other unit list aliases โ€” so that time definition up there could not have been shortened to year;day;hms. Nope. Not allowed. ๐Ÿ™…โ€โ™€๏ธ

As always, run units --check to make sure the units listed in your unit list aliases are conformable. Do it. It's free. ๐Ÿซถ


โœจ NUMERIC OUTPUT FORMAT โœจ

By default, units shows results to eight significant digits in general number format. Cute, right? But you can absolutely switch it up with --exponential, --digits, and --output-format. ๐Ÿ’…

  • --exponential sets an exponential format (a.k.a. scientific notation) like the one in the original Unix units program.
  • --digits lets you specify a different number of significant digits.
  • --output-format gives you full control over the output's appearance using the format for the printf function in the C programming language.

If you only wanna change the number of significant digits or specify the exponential format type, just use --digits and --exponential. Simple. Iconic. ๐ŸŒธ

But --output-format? That one affords the greatest control of the output appearance โ€” at the cost of requiring at least rudimentary knowledge of the printf format syntax. It's giving "worth it but do your homework." See Invoking Units for descriptions of these options. ๐Ÿ“–

Format Specification

The format specification recognized with --output-format is a subset of the one for printf. The format specification has the form:

%[flags][width][.precision]type

It must begin with %, and it must end with a floating-point type specifier:

  • g or G โ€” specifies the number of significant digits
  • e or E โ€” scientific notation
  • f โ€” fixed-point decimal

The ISO C99 standard added the F type for fixed-point decimal and the a and A types for hexadecimal floating point; these types are allowed with compilers that support them. Type length modifiers (like L to indicate a long double) are inapplicable and are not allowed. ๐Ÿšซ

The default format for units is %.8g; for greater precision, you could specify -o %.15g. โœจ

Now, the tea on g and G: they use exponential format whenever the exponent would be less than -4, so the value 0.000013 displays as 1.3e-005. These types also use exponential notation when the exponent is greater than or equal to the precision โ€” so with the default format, the value 5 ร— 10^7 displays as 50000000 and the value 5 ร— 10^8 displays as 5e+008. ๐Ÿ˜ฎ

If you prefer fixed-point display, you might specify -o %.8f โ€” however, small numbers will display very few significant digits, and values less than 5 ร— 10^-8 will show nothing but zeros. Nothing. Just zeros. ๐Ÿ’€

The format specification may include one or more optional flags: +, (space), #, -, or 0 (the digit zero). The digit-grouping flag ' is allowed with compilers that support it. Flags are followed by an optional value for the minimum field width, and an optional precision specification that begins with a period (e.g., .6). The field width includes the digits, decimal point, the exponent, thousands separators (with the digit-grouping flag), and the sign if any of these are shown. ๐Ÿงฎ

Flags

  • + โ€” causes the output to have a sign (+ or -).
  • (space) โ€” similar to the + flag, except that when the value is positive, it is prefixed with a space rather than a plus sign; this flag is ignored if the + flag is also given.
  • # โ€” causes the output value to contain a decimal point in all cases; by default, the output contains a decimal point only if there are digits (which can be trailing zeros) to the right of the point. With the g or G types, the # flag also prevents the suppression of trailing zeros.
  • ' โ€” the digit-grouping flag; shows a thousands separator in digits to the left of the decimal point.
  • - โ€” the output value is left aligned within the specified field width.
  • 0 (the digit zero) โ€” if a field width greater than needed to show the output value is specified, causes the output value to be left padded with zeros until the specified field width is reached. The 0 flag has no effect if the - (left align) flag is given.

The + or flag could be useful if conversions might include positive and negative results, and you wanted to align the decimal points in exponential notation. ๐ŸŽฏ

The digit-grouping flag ' can be useful when displaying large numbers in fixed-point decimal; for example, with the format %f,

You have: mile
You want: microfurlong
        * 8000000.000000
        / 0.000000

the magnitude of the first result may not be immediately obvious without counting the digits to the left of the decimal point. ๐Ÿ˜ตโ€๐Ÿ’ซ If the thousands separator is the comma (,), the output with the format %'f might be

You have: mile
You want: microfurlong
        * 8,000,000.000000
        / 0.000000

making the magnitude readily apparent. ๐ŸŒˆ Unfortunately, few compilers support the digit-grouping flag. Sad. ๐Ÿ˜ญ

And here's the 0 flag in action โ€” with the format %011.6f,

You have: troypound
You want: grain
        * 5760.000000
        / 0000.000174

Field Width

By default, the output value is left aligned and shown with the minimum width necessary for the specified (or default) precision. If a field width greater than this is specified, the value shown is right aligned, and padded on the left with enough spaces to provide the specified field width. ๐Ÿซง

A width specification is typically used with fixed-point decimal to have columns of numbers align at the decimal point; this arguably is less useful with units than with long columnar output, but it may nonetheless assist in quickly assessing the relative magnitudes of results. So like... it's a vibe. A useful vibe. ๐Ÿ’–

For example, with the format %12.6f,

You have: km
You want: in
        * 39370.078740
        /     0.000025
You have: km
You want: rod
        *   198.838782
        /     0.005029
You have: km
You want: furlong
        *     4.970970
        /     0.201168

See how everything lines up?? Chef's kiss. ๐Ÿ‘‘

Precision

The meaning of "precision" depends on the format type:

  • With g or G, it specifies the number of significant digits (like the --digits option).
  • With e, E, f, or F, it specifies the maximum number of digits to be shown after the decimal point.

With the g and G format types, trailing zeros are suppressed, so the results may sometimes have fewer digits than the specified precision (as indicated above, the # flag causes trailing zeros to be displayed). ๐Ÿ™ˆ

The default precision is 6, so %g is equivalent to %.6g, and would show the output to six significant digits. Similarly, %e or %f would show the output with six digits after the decimal point. Easy math, bestie. โœจ

The C printf function allows a precision of arbitrary size, whether or not all of the digits are meaningful. With most compilers, the maximum internal precision with units is 15 decimal digits (or 13 hexadecimal digits). With the --digits option, you are limited to the maximum internal precision; with the --output-format option, you may specify a precision greater than this, but it may not be meaningful. โš ๏ธ

In some cases, specifying excess precision can result in rounding artifacts. Do not trust the extra digits, they are lying to you. ๐Ÿ’€

For example, a pound is exactly 7000 grains, but with the format %.18g, the output might be

You have: pound
You want: grain
        * 6999.9999999999991
        / 0.00014285714285714287

With the format %.25g you might get the following:

You have: 1/3
You want:
        Definition: 0.333333333333333314829616256247

In this case the displayed value includes a series of digits that represent the underlying binary floating-point approximation to 1/3 but are not meaningful for the desired computation. ๐Ÿ˜ญ In general, the result with excess precision is system dependent. The precision affects only the display of numbers; if a result relies on physical constants that are not known to the specified precision, the number of physically meaningful digits may be less than the number of digits shown. ๐Ÿงš

See the documentation for printf for more detailed descriptions of the format specification. ๐Ÿ“š

Heads up bestie: the --output-format option is incompatible with the --exponential or --digits options; if the former is given in combination with either of the latter, the format is controlled by the last option given. Last one wins. Periodt. ๐Ÿ’…

okay so this next bit is where units gets โœจculturally awareโœจ and honestly? it's giving world tour. ๐ŸŒ


๐ŸŒธ LOCALIZATION ๐ŸŒธ

Some units have different values in different locations. Bestie, that's just how it is. The localization feature accommodates this by letting a units data file specify definitions that depend on the user's locale. ๐Ÿ’…

๐ŸŽ€ Locale

A locale is a subset of a user's environment that says what language and country the user is in, plus some attendant preferences, like how dates get formatted. โœจ

The units program tries to figure out the locale from the POSIX setlocale function; if that can't be done, units peeks at the environment variables LC_CTYPE and LANG. ๐Ÿ‘€

On POSIX systems, a locale looks like language_*country*, where language is the two-character code from ISO 639-1 and country is the two-character code from ISO 3166-1; language is lower case and country is upper case. For example, the POSIX locale for the United Kingdom is en_GB. ๐Ÿ‡ฌ๐Ÿ‡ง

On systems running Microsoft Windows, the value returned by setlocale is different from the POSIX one; units tries to map the Windows value to a POSIX value using a table in the file locale_map.txt, which lives in the same directory as the other data files. That file includes entries for many combinations of language and country, and you can extend it to include other combinations. ๐Ÿ—บ๏ธ

The locale_map.txt file is made of two tab-separated columns; each entry looks like

Windows-locale   POSIX-locale

where POSIX-locale is as described above, and Windows-locale typically spells out both the language and country. For example, the entry for the United States is

English_United States   en_US

You can force units to run in a desired locale by using the -l option. ๐Ÿซถ

So to create unit definitions for a particular locale, you start a block of definitions in a unit datafile with !locale followed by a locale name. The ! must be the first character on the line. The units program reads the following definitions only if the current locale matches. You close the block of localized units with !endlocale. Here's an example, which defines the British gallon:

!locale en_GB
gallon       4.54609 liter
!endlocale

๐Ÿฆ‹ Additional Localization

Sometimes the locale just isn't enough to pin down unit preferences. ๐Ÿ˜ญ There could be regional preferences, or a company could have its own specific preferences. Though it's probably uncommon, such differences could arise with the choice of English customary units outside of English-speaking countries. To address this, units lets you specify definitions that depend on environment variable settings. The environment variables can be controlled based on the current locale, or the user can set them to force a particular group of definitions. ๐Ÿ”ฅ

A conditional block of definitions in a units data file begins with either !var or !varnot followed by an environment variable name and then a space separated list of values. The leading ! must appear in the first column of a units data file, and the conditional block is terminated by !endvar.

  • Definitions in blocks beginning with !var are executed only if the environment variable is exactly equal to one of the listed values.
  • Definitions in blocks beginning with !varnot are executed only if the environment variable does not equal any of the list values.

The inch has long been a customary measure of length in many places. The word comes from the Latin uncia, meaning "one twelfth," referring to its relationship with the foot. By the 20th century, the inch was officially defined in English-speaking countries relative to the yard, but until 1959, the yard differed slightly among those countries. In France the customary inch, which was displaced in 1799 by the meter, had a different length based on a french foot. ๐Ÿฅ

These customary definitions could be accommodated as follows:

!var INCH_UNIT usa
yard          3600|3937 m
!endvar
!var INCH_UNIT canada
yard          0.9144 meter
!endvar
!var INCH_UNIT uk
yard          0.91439841 meter
!endvar
!var INCH_UNIT canada uk usa
foot          1|3 yard
inch          1|12 foot
!endvar
!var INCH_UNIT france
foot          144|443.296 m
inch          1|12 foot
line          1|12 inch
!endvar
!varnot INCH_UNIT usa uk france canada
!message Unknown value for INCH_UNIT
!endvar

When units reads the above definitions it will check the environment variable INCH_UNIT and load only the definitions for the appropriate section. If INCH_UNIT is unset or is not set to one of the four values listed, then units will run the last block. In this case that block uses the !message command to display a warning message. โš ๏ธ Alternatively that block could set default values.

In order to create default values that get overridden by user settings, the data file can use the !set command, which sets an environment variable only if it is not already set; these settings are only for the current units invocation and do not persist. So if the example above were preceded by !set INCH_UNIT france, then this would make france the default value for INCH_UNIT. If the user had set the variable in the environment before invoking units, then units would use the user's value. ๐Ÿ‘‘

To link these settings to the user's locale you combine the !set command with the !locale command. If you wanted to combine the above example with suitable locales you could do it by preceding the above definition with the following:

!locale en_US
!set INCH_UNIT usa
!endlocale
!locale en_GB
!set INCH_UNIT uk
!endlocale
!locale en_CA
!set INCH_UNIT canada
!endlocale
!locale fr_FR
!set INCH_UNIT france
!endlocale
!set INCH_UNIT france

These definitions set the overall default for INCH_UNIT to france and set default values for four locales appropriately. The overall default setting comes last so that it only applies when INCH_UNIT was not set by one of the other commands or by the user. โœจ

๐Ÿšจ If the variable given after !var or !varnot is undefined, then units prints an error message and ignores the definitions that follow. Use !set to create defaults to prevent this situation from arising. The -c option only checks the definitions that are active for the current environment and locale, so when adding new definitions take care to check that all cases give rise to a well defined set of definitions. ๐Ÿ’€

๐ŸŒˆ ENVIRONMENT VARIABLES ๐ŸŒˆ

The units program uses the following environment variables:

  • HOME โ€” Specifies the location of your home directory; it's used by units to find a personal units data file .units. On systems running Microsoft Windows, the file is unitdef.units, and if HOME does not exist, units tries to determine your home directory from the HOMEDRIVE and HOMEPATH environment variables; if these variables do not exist, units finally tries USERPROFILE โ€” typically C:\Users\username (Windows Vista and Windows 7) or C:\Documents and Settings\username (Windows XP). ๐Ÿ 
  • LC_CTYPE, LANG โ€” Checked to determine the locale if units cannot obtain it from the operating system. Sections of the default main units data file are specific to certain locales. ๐Ÿ—ฃ๏ธ
  • MYUNITSFILE โ€” Specifies your personal units data file. If this variable exists, units uses its value rather than searching your home directory for .units. The personal units file will not be loaded if any data files are given using the -f option. ๐Ÿ’พ
  • PAGER โ€” Specifies the pager to use for help and for displaying the conformable units. The help function browses the units database and calls the pager using the +nn syntax for specifying a line number. The default pager is more; PAGER can be used to specify alternatives such as less, pg, emacs, or vi. ๐Ÿ“–
  • UNITS_ENGLISH โ€” Set to either US or GB to choose United States or British volume definitions, overriding the default from your locale. ๐Ÿ‡บ๐Ÿ‡ธ๐Ÿ‡ฌ๐Ÿ‡ง
  • UNITSFILE โ€” Specifies the units data file to use (instead of the default). You can only specify a single units data file using this environment variable. If units data files are given using the -f option, the file specified by UNITSFILE will not be loaded unless the -f option is given with the empty string (units -f ""). โš ๏ธ
  • UNITSLOCALEMAP โ€” Windows only; this variable has no effect on Unix-like systems. Specifies the units locale map file to use (instead of the default). This variable seldom needs to be set, but you can use it to ensure that the locale map file will be found if you specify a location for the units data file using either the -f option or the UNITSFILE environment variable, and that location does not also contain the locale map file. ๐ŸชŸ
  • UNITS_SYSTEM โ€” This environment variable is used in the default main data file to select CGS measurement systems. Currently supported systems are esu, emu, gauss[ian], hlu, natural, natural-gauss, planck, planck-red, hartree and si. The default is si. โš›๏ธ

and bestie we are SO not done yet, keep scrolling ๐Ÿ’–

โœจ DATA FILES โœจ

okay bestie, so units rolls up with six default data files and you're gonna want to know all of them ๐Ÿ’–

  • the main data file, definitions.units
  • the atomic masses of the elements, elements.units
  • currency exchange rates, currency.units
  • cryptocurrency prices, crypto.units
  • precious metals prices, metal_prices.units
  • and the US Consumer Price Index, cpi.units

the last five files get loaded via !include directives inside the main file (peep Database Command Syntax for the deets ๐Ÿ‘€).

there's also an optional personal units data file called .units (unitdef.units if you're on Windows ๐ŸชŸ) that lives in your home directory. it gets its own whole moment in Units Data Files.

on Unix-like systems, the data files are typically chilling in /usr/share/units if units came with your OS, or in /usr/local/share/units if you compiled units from the source distribution. and listen โ€” currency.units, crypto.units, metal_prices.units, and cpi.units are symbolic links to another location. sneaky little links, iconic behavior ๐Ÿ’…

on Microsoft Windows systems, the files may sit in those same spots if Unix-like commands are available, a Unix-like file structure is present (like C:/usr/local), and units is compiled from the source distribution. if Unix-like commands aren't available, the more common location is C:\Program Files (x86)\GNU\units (for 64-bit Windows installations) or C:\Program Files\GNU\units (for 32-bit installations).

and if units came from the GNU Win32 Project (http://gnuwin32.sourceforge.net/), the files commonly live in C:\Program Files\GnuWin32\share\units.

lowkey important: if the default main units data file is not an absolute pathname, units will go looking for the file in the directory that contains the units program. if it's not there, units checks a directory ../share/units relative to the directory with the units program. ๐Ÿ•ต๏ธ

you can figure out where the files are by running units --version. and running units --info gives you extra tea about the files, how units will try to find them, and the status of the related environment variables. go off โœจ


๐Ÿฆ‹ UNICODE SUPPORT ๐Ÿฆ‹

the standard units data file is in Unicode, using UTF-8 encoding. most definitions stick to plain ASCII (that's code points U+0000 through U+007F), and the definitions that do use non-ASCII characters show up in blocks that start with !utf8 and end with !endutf8. ๐ŸŽ€

those non-ASCII definitions load only if the platform and the locale support UTF-8. platform support is decided when units is compiled; the locale gets checked at every single invocation of units. wanna see if your version of units has Unicode support? just run the program with the --version option. easy peasy ๐Ÿ“

when Unicode support is available, units checks every line within UTF-8 blocks in all of the units data files for invalid or non-printing UTF-8 sequences. if it finds any, units ignores the entire line. besides checking validity, units also figures out the display width of non-ASCII characters so the pointer lands in the right spot in some error messages, and so columns line up for the search and ? commands. alignment queen ๐Ÿ‘‘

Microsoft Windows supports UTF-8 in console applications running in Windows Terminal โ€” but UTF-8 is not supported in applications running in the older Windows Console Host (see Unicode Support on Windows). and nope, the UTF-16 and UTF-32 encodings are not supported on any platforms. ๐Ÿ’€

if Unicode support is available and you add definitions containing non-ASCII UTF-8 characters to a units data file, those definitions should be wrapped in !utf8 ... !endutf8 so they only load when Unicode support is there. as usual, the ! must appear as the first character on the line. and like it says in Units Data Files, it's usually best to put definitions like that in supplemental data files linked by an !include command, or in a personal units data file. ๐Ÿซถ

when Unicode support is not available, units makes zero assumptions about character encoding โ€” except that characters in the range 00โ€“7F hexadecimal correspond to ASCII encoding. non-ASCII characters are just sequences of bytes with no special meanings. for definitions in supplementary units data files, you can use any encoding consistent with that assumption. for example, if you wanna use non-ASCII characters in definitions while running units under Windows, you can use a character set like Windows "ANSI" (code page 1252 in the US and Western Europe) โ€” and if you do that, the console code page must be set to the same encoding or the characters won't display right. you can even use UTF-8, though some messages may be improperly aligned, and units will not detect invalid UTF-8 sequences. and if you use UTF-8 encoding when Unicode support isn't available, you should put any definitions with non-ASCII characters outside !utf8 ... !endutf8 blocks โ€” otherwise they'll just get ignored. rude but true ๐Ÿ˜ญ

except for code examples, typeset material usually uses the Unicode symbols for mathematical operators. to make copying and pasting from those sources easier, several typographical characters get converted to the ASCII operators used in units:

  • the figure dash (U+2012), minus (-; U+2212), and en dash (โ€“; U+2013) are converted to the operator -
  • the multiplication sign (ร—; U+00D7), N-ary times operator (U+2A09), dot operator (โ‹…; U+22C5), and middle dot (ยท; U+00B7) are converted to the operator *
  • the division sign (รท; U+00F7) is converted to the operator /
  • and the fraction slash (U+2044) is converted to the operator |

๐ŸŒˆ Unicode Support on Windows ๐ŸŒˆ

Microsoft Windows supports UTF-8 in console applications running in Windows Terminal, but not in applications running in the older Windows Console Host. in Windows Terminal, the code page must be set to 65001 for UTF-8 to be enabled. with the UTF-8 code page, running units -V might show you this:

GNU Units version 2.24
Without readline, with UTF-8, locale English_United States (en_US)

two values are shown for the locale: the first is the one returned by the system; the second is the POSIX value that the system value gets mapped to. โœจ

with a different code page, the result might be:

GNU Units version 2.24
Without readline, with UTF-8 (disabled), locale English_United States (en_US)
To enable UTF-8: set code page to 65001

and if units is running in Windows Console Host, no matter what the code page is, the result might be:

GNU Units version 2.24
Without readline, with UTF-8 (disabled), locale English_United States (en_US)
To enable UTF-8: run in Windows Terminal and set code page to 65001

the UTF-8 code page can be set by running chcp 65001. ๐ŸŽ€

heads up: as of late 2024, the Windows build of units does not identify characters โ€” typically East Asian ones โ€” that occupy more than one column, and error messages involving those characters may not be properly aligned. so your vibes might be off by a column or two ๐Ÿ’€

๐ŸŽ€ READLINE SUPPORT ๐ŸŽ€

if the readline package has been compiled in, then when units is used interactively, you get numerous command line editing features. to check if your version of units includes readline, run the program with the --version option. ๐Ÿ‘‘

for complete information about readline, go consult the documentation for the readline package. without any configuration, units lets you edit in the style of emacs. and particularly useful with units? the completion commands. ๐Ÿฆ‹

type a few characters and then hit ESC followed by ?, and units will show you a list of all the units that start with the characters you typed. for example, if you type metr and then request completion, you'll see something like this:

You have: metr
metre             metriccup         metrichorsepower  metrictenth
metretes          metricfifth       metricounce       metricton
metriccarat       metricgrain       metricquart       metricyarncount
You have: metr

if there's a unique way to complete a unit name, you can hit the TAB key and units will fill in the rest of the unit name for you. if units beeps? that means there's no unique completion. press TAB a second time and it'll print the list of all completions. bestie really said "here are your options" ๐Ÿ’…

the readline library also keeps a history of the values you enter. you can move through that history using the up and down arrows. the history gets saved to the file .units_history in your home directory so it persists across multiple units invocations. if you wanna keep work for a certain project separate, you can change the history filename using the --history option. you could, for example, make an alias for units to units --history .units_history so that units would save separate history in the current directory. the length of each history file is limited to 5000 lines. and note also that if you run several concurrent copies of units, each one will save its new history to the history file upon exit. ๐Ÿ“

๐Ÿ’ธ UPDATING CURRENCY EXCHANGE RATES AND CPI ๐Ÿ’ธ

Currency Exchange Rates

okay bestie so here's the tea: the units program database ships with currency exchange rates and prices for some precious metals. and likeโ€ฆ those values change over time. sometimes very rapidly. and units literally cannot give you real-time values, no cap. so to update the exchange rates you run units_cur, which rewrites the file containing the currency rates โ€” typically /var/lib/units/currency.units or /usr/local/com/units/currency.units on a Unix-like system, or C:\Program Files (x86)\GNU\units\definitions.units on a Windows system. ๐Ÿซถ

This program requires Python 3 (https://www.python.org). and it must be run with suitable permissions to write that file, so like, mind your perms bestie. To keep the rates updated automatically, run it using a cron job on a Unix-like system, or a similar scheduling program on a different system. โœจ

Reliable free sources of currency exchange rates have been annoyingly ephemeral โ€” it's giving unreliable narrator tbh. The program currently supports several sources:

  • ExchangeRate-API.com (https://www.exchangerate-api.com). The default currency server. Allows open access without an API key, with unlimited API requests. Rates update once a day, the US dollar (USD) is the default base currency, and you can choose your base currency with the -b option described below. You can optionally sign up for an API key to access paid benefits such as faster data update rates.
  • FloatRates (https://www/floatrates.com). The US dollar (USD) is the default base currency. You can change the base currency with the -b option described below. Allowable base currencies are listed on the FloatRates website. Exchange rates update daily.
  • The European Central Bank (https://www.ecb.europa.eu). The base currency is always the euro (EUR). Exchange rates update daily. This source offers a more limited list of currencies than the others.
  • Fixer (https://fixer.io). Registration for a free API key is required. With a free API key, base currency is the euro; exchange rates are updated hourly, the service has a limit of 1,000 API calls per month, and SSL encryption (https protocol) is not available. Most of these restrictions are eliminated or reduced with paid plans.
  • open exchange rates (https://openexchangerates.org). Registration for a free API key is required. With a free API key, the base currency is the US dollar; exchange rates are updated hourly, and there is a limit of 1,000 API calls per month. Most of these restrictions are eliminated or reduced with paid plans.

The default source is FloatRates; you can select a different one using the -s option described below. ๐Ÿ’…


Crypto and Precious Metals Prices

Cryptocurrency prices are obtained from coingecko (coingecko.com). Precious metals pricing is obtained from Packetizer (www.packetizer.com); this site updates once per day. ๐Ÿช™


US Consumer Price Index

The units program includes the US Consumer Price Index (CPI) published by the US Bureau of Labor Statistics: specifically, the Consumer Price Index for All Urban Consumers (CPI-U), not seasonally adjustedโ€”Series CUUR0000SA0. ๐Ÿ“Š

The units_cur command updates the CPI and saves the result in cpi.units in the same location as currency.units. The data are obtained via the BLS Public Data API (https://www.bls.gov/developers/). These data update once a month. When units_cur runs it will only attempt to update the CPI data if the current CPI data file is from a previous month, or if the current date is after the 18th of the month.


Invoking units_cur

You invoke units_cur like this:

units_cur [options] [currency_file] [crypto_file] [metals_file] [cpi_file]

By default, the output is written to the default currency, crypto, metals, and CPI files described above; this is usually what you want, because this is where units looks for the files. If you wish, you can specify different filenames on the command line and units_cur will write the data to those files. If you give - for a file it will write to standard output. The special filename . skips the update for that file. (iconic behaviour honestly)

The following options are available:

  • -h, --help โ€” Print a summary of the options for units_cur.
  • -V, --version โ€” Print the units_cur version number.
  • -v, --verbose โ€” Give slightly more verbose output when attempting to update currency exchange rates.
  • -c coingecko,packetizer, --crypto coingecko,packetizer โ€” Set crypto data source (default: coingecko).
  • -s source, --source source โ€” Specify the source for currency exchange rates; currently supported values are floatrates (for FloatRates), eubank (for the European Central Bank), fixer (for Fixer), and openexchangerates (for open exchange rates); the last two require an API key to be given with the -k option.
  • -b base, --base base โ€” Set the base currency (when allowed by the site providing the data). base should be a 3-letter ISO currency code, e.g., USD. The specified currency will be the primitive currency unit used by units. You may find it convenient to specify your local currency. Conversions may be more accurate and you will be able to convert to your currency by simply hitting Enter at the You want: prompt. This option is ignored if the source does not allow specifying the base currency. (Currently only floatrates supports this option.)
  • -k key, --key key โ€” Set the API key to key for currency sources that require it.
  • --blskey BLSkey โ€” Set the US Bureau of Labor Statistics (BLS) key for fetching CPI data. Without a BLS key you should be able to fetch the CPI data exactly one time per day. If you want to use a key you must request a personal key from BLS.

๐Ÿ“š DATABASE COMMAND SYNTAX ๐Ÿ“š

okay so this is the whole syntax menu for the definitions file, bestie. every single one, no skips ๐Ÿ’–

  • unit definition Define a regular unit.
  • prefix- definition Define a prefix.
  • ``` funcname(var) noerror units=[in-units,out-units] domain=[x1,x2] range=[y1,y2] definition(var) ; inverse(funcname)
Define a nonlinear unit or unit function. The four optional keywords `noerror`, `units=`, `range=` and `domain=` can appear in any order. The definition of the inverse is optional.
- `tabname[out-units] noerror pair-list`
Define a piecewise linear unit. The pair list gives the points on the table listed in ascending order. The `noerror` keyword is optional.
- `!endlocale`
End a block of definitions beginning with `!locale`
- `!endutf8`
End a block of definitions begun with `!utf8`
- `!endvar`
End a block of definitions begun with `!var` or `!varnot`
- `!include file`
Include the specified file.
- `!locale value`
Load the following definitions only of the locale is set to *value*.
- `!message text`
Display *text* when the database is read unless the quiet option (`-q`) is enabled. If you omit *text*, then `units` will display a blank line. Messages will also appear in the log file.
- `!prompt text`
Prefix the `You have:` prompt with the specified *text*. If you omit *text*, then any existing prefix is canceled.
- `!set variable value`
Sets the environment variable, *variable*, to the specified *value* only if it is not already set.
- `!unitlist alias definition`
Define a unit list alias.
- `!utf8`
Load the following definitions only if `units` is running with UTF-8 enabled.
- `!var envar value-list`
Load the block of definitions that follows only if the environment variable *envar* is set to one of the values listed in the space-separated *value* list. If *envar* is not set, `units` prints an error message and ignores the block of definitions.
- `!varnot envar value-list`
Load the block of definitions that follows only if the environment variable *envar* is set to *value* that is not listed in the space-separated *value* list. If *envar* is not set, `units` prints an error message and ignores the block of definitions.

---

# ๐Ÿ“‚ FILES ๐Ÿ“‚

- `/usr/share/units/definitions.units` โ€” the standard units data file ๐ŸŒธ

---

# ๐Ÿ‘‘ AUTHOR ๐Ÿ‘‘

`units` was written by Adrian Mariano

---

that's a wrap on the whole page bestie, we literally made it to the end ๐ŸŽ€ this version is the `UNITS(1)` page, dated **29 March 2026** โ€” go forth and convert things with main character energy โœจ๐Ÿ’…๐Ÿฆ‹
๐Ÿ“ฆ where this page comes from