Computing with Units

Version 1.89.J01 - 3 April 2012. (This page updated 5 April 2014.)


1. Overview

Units is a program for computations on values expressed in terms of different measurement units. It is an advanced calculator that takes care of the units.

Previously this place contained an applet where you could try the calculations. At present, Java blocks unsigned applets, so you can only see a screenshot of a calculation:

We calculated here the time taken by a stone thrown into a 50-foot well to reach the bottom. We used the well-known formula: square root of 2h/a where h is the height of the fall and a is the gravitational acceleration, which we knew to be 981 cm/sec^2. Note that we used different units of length for h and a, and the calculator made the necessary conversion behind the scenes.

If you want to try Units, you have to install it in on your computer. As it is written in Java, you can use it under any operating system that supports Java Runtime Environment (JRE) release 1.5.0 or later. To install Units, download the Java archive (JAR) file that contains the executable Java classes. Save the JAR file in any directory, under any name of your choice, with extension .jar. If your system has an association of .jar files with javaw command (which is usually set up when you install JRE), just double-click on the JAR file icon. If this does not work, you can type

java -jar jarfile

at the command prompt, where jarfile is the name you gave to the JAR file. Each way should open a window like the one shown above.

Units supports complicated expressions and a number of mathematical functions, as well as units defined by linear, nonlinear, and piecewise-linear functions. See under Expressions for detailed specifications.

Units has an extensive data base that, besides units from different domains, cultures, and periods, contains many constants of nature, such as:

pi          ratio of circumference to diameter
c           speed of light
e           charge on an electron
h           Planck's constant

As an example of using these constants, suppose you want to find the wavelength, in meters, of a 144 MHz radio wave. It is obtained by dividing the speed of light by the frequency. The speed of light is 186282.39 miles/sec. But, you do not need to know this exact number. Just enter this after You have:

c / 144 MHz

Enter m after You want and hit the Enter key. You will get this result:

c /144MHz = 2.0818921 m

Sometimes you may want to express the result as a sum of different units, for example, to find what is 2 m in feet and inches. To try this, enter 2 m after You have. Then enter after You want:

ft;in
and hit Enter. You will get this result:
2 m = 6 ft + 6.7401575 in

Other examples of computations:

Feet and inches to metric: 6 ft + 7 in = 200.66 cm
Time in mixed units:       2 years = 17531 hours + 37 min + 31.949357 sec
Angle in mixed units:      radian = 57 deg + 17 ' + 44.806247 "
Fahrenheit to Celsius:     tempF(97) = tempC(36.111111)
Electron flow:             5 mA = 3.1207548e16 e/sec
Energy of a photon:        h * c / 5896 angstrom = 2.1028526 eV
Mass to energy:            1 g * c^2 = 21.480764 kilotons tnt
Baking:                    2 cups flour_sifted = 226.79619 g
Weight as force:           5 force pounds = 22.241108 newton

(The unit pound is a unit of mass. To get force, you multiply it by force, which is a name for standard gravity acceleration. Note that g, customarily used for that constant, is already taken as the standard abbreviation for the gram).

You can explore the units data base with the help of the four buttons under You have field. By entering any string in You have field and pressing the Search button, you obtain a list of all unit names that contain that string as a substring. For example, if you enter year at You have and press Search, you get a list of about 25 different kinds of year, including marsyear and julianyear.

Pressing Definition displays this in the result area:

year = tropicalyear = 365.242198781 day = 31556926 s,

which tells you that year is defined as equal to tropicalyear, which is equal to 365.242198781 days or 31556926 seconds.

If you now enter tropicalyear at You have and press the Source button, you open a browser on the unit data base at the place containing the definition of tropicalyear. You find there a long comment explaining that unit. You may then freely browse the data base to find other units and facts about them.

Pressing Conformable units will give you a list of all units for measuring the same property as tropicalyear, namely the length of a time interval. The list contains over 80 units.

With Units installed on your computer, you can use it interactively from command line, or invoke it from scripts. It imitates then almost exactly the behavior of GNU Units from which it has evolved. See Command interface for details.

You also have a possibility to modify the file that contains unit definitions, or add your own definitions in separate file(s).

The complete package containing the JAR and the Java source can be downloaded as a gzipped tar file from the SourceForge project page.


2. Expressions

You use expressions to specify computations on physical and other quantities. A quantity is expressed as the product of a numerical value and a unit of measurement. Each quantity has a dimension that is either one of the basic dimensions such as length or mass, or a combination of those. For example, 7 mph is the product of number 7 and unit mile/hour; it has the dimension of length divided by time. For a deeper discussion, see articles on physical quantity and dimensional analysis.

For each basic dimension, Units has one primitive unit: meter for length, gram for mass, second for time, etc.. The data base defines each non-primitive unit in such a way that it can be converted to a combination of primitive units. For example, mile is defined as equal to 1609.344 m and hour to 3600 s. Behind the scenes, Units replaces the units you specify by these values, so 7 mph becomes:

7 mph = 7 * mile/hour = 7 * (1609.344*m)/(3600*s) = 3.12928 m/s

This is the quantity 7 mph reduced to primitive units. The result of a computation can, in particular, be reduced to a number, which can be regarded as a dimensionless quantity:

17 m / 120 in = 5.5774278

2.1. Unit names

In your expressions, you can use any units named in the units data base. You find there all standard abbreviations, such as ft for foot, m for meter, or A for ampere.

For readability, you may use plural form of unit names, thus writing, for example, seconds instead for second. If the string you specified does not appear in the data base, Units will try to ignore the suffix s or es. It will also try to remove the suffix ies and replace it by y. The data base contains also some irregular plurals such as feet.

2.2. Prefixes

The data base defines all standard metric prefixes as numbers. Concatenating a prefix in front of a unit name means multiplication by that number. Thus, the data base does not contain definitions of units such as milligram or millimeter. Instead, it defines milli- and m- as prefixes that you can apply to gram, g, meter, or m, obtaining milligram, mm, etc..

Only one prefix is permitted per unit, so micromicrofarad will fail. However, micro is a number, so micro microfarad will work and mean .000001 microfarad.

2.3. Numbers

Numbers are written using standard notation, with or without decimal point. They may be written with an exponent, for example 3.43e-8 to mean 3.43 times 10 to the power of -8.

2.4. Multiplication and division

By writng a quantity as 1.2 meter or 1.2m, you really mean 1.2 multiplied by meter. This is multiplication denoted by juxtaposition. You can use juxtaposition, with or without space, to denote multiplication also in other contexts, whenever you find it convenient.

In addition to that, you indicate multiplication in the usual way by an asterisk (*). Division is indicated by a slash (/) or per. Division of numbers can also be indicated by the vertical dash (|). Examples:

10cm 15cm 1m = 15 liters
7 * furlongs per fortnight = 0.0011641667 m/s
1|2 meter = 0.5 m

The multiplication operator * has the same precedence as / and per; these operators are evaluated from left to right.

Multiplication using juxtaposition has higher precedence than * and division. Thus, m/s s/day does not mean (m/s)*(s/day) but m/(s*s)/day = m/(s*s*day), which has dimension of length per time cubed. Similarly, 1/2 meter means 1/(2 meter) = .5/meter, which is probably not what you would intend.

The division operator | has precedence over both kinds of multiplication, so you can write 'half a meter' as 1|2 meter. This operator can only be applied to numbers.

2.5. Addition and subtraction

Sums are written with the plus (+) and minus (-). Examples:

2 hours + 23 minutes - 32 seconds = 8548 seconds
12 ft + 3 in = 373.38 cm
2 btu + 450 ft lbf = 2720.2298 J

The quantities which are added together must have identical dimensions. For example, 12 printerspoint + 4 heredium results in this message:

Sum of non-conformable values:
  0.0042175176 m
  20186.726 m^2.

Plus and minus can be used as unary operators. Minus as a unary operator negates the numerical value of its operand.

2.6. Exponents

Exponents are specified using the operator ^ or **. The exponent must be a number. As usual, x^(1/n) means the n-th root of x, and x^(-n) means 1/(x^n):

cm^3 = 0.00026417205 gallon
100 ft**3 = 2831.6847 liters
acre^(1/2) = 208.71074 feet
(400 W/m^2 / stefanboltzmann)^0.25 = 289.80881 K
2^-0.5 = 0.70710678

An exponent n or 1/n where n is not an integer can only be applied to a number. You can take the n-th root of non-numeric quantity only if that quantity is an n-th power:

foot^pi =
  Non-numeric base, 0.3048 m, for exponent 3.1415927.

hectare**(1/3) =
  10000 m^2 is not a cube.

An exponent like 2^3^2 is evaluated right to left.

The operators ^ and ** have precedence over multiplication and division, so 100 ft**3 is 100 cubic feet, not (100 ft)**3. On the other hand, they have a lower priority than prefixing and |, so centimeter^3 means cubic centimeter, but centi meter^3 is 1/100 of a cubic meter. The square root of two thirds can be written as 2|3^1|2.

Abbreviation. You may concatenate a one-digit exponent, 2 through 9, directly after a unit name. In this way you abbreviate foot^3 to foot3 and sec^2 to sec2.
But beware: $ 2 means two dollars, but $2 means one dollar squared.

2.7. Functions

Units provides a number of functions that you can use in your computation. You invoke a function in the usual way, by writing its name followed by the argument in parentheses. Some of them are built into the program, and some are defined in the units data base.

Built-in functions

The built-in functions include sin, cos, tan, their inverses asin, acos, atan, and:

ln        natural logarithm
log       base-10 logarithm
log2      base-2  logarithm
exp       exponential
sqrt      square root, sqrt(x) = x^(1/2)
cuberoot  cube root, cuberoot(x) = x^(1/3)

The argument of sin, cos, and tan must be a number or an angle. They return a number.

The argument of asin, acos, atan, ln, log, log2, and exp must be a number. The first three return an angle and the remaining return a number.

The argument of sqrt and cuberoot must be a number, or a quantity that is a square or a cube.

Defined functions

Some of the functions defined in the data base are:
circlearea  area of circle with given radius
pH          converts pH value to moles per liter
tempF       converts temperature Fahrenheit to temperature Kelvin
wiregauge   converts wire gauge to wire thickness

Most of them are used to handle nonlinear scales, as explained under Nonlinear meaures.

By preceding a function's name with a tilde (~) you obtain an inverse of that function:

circlearea(5cm) = 78.539816 cm^2  ~circlearea(78.539816 cm^2) = 5 cm
pH(8) = 1.0E-8 mol/liter          ~pH(1.0E-8 mol/liter) = 8
tempF(97) = 309.26111 K           ~tempF(309.26111 K) = 96.999998
wiregauge(11) = 2.3048468 mm      ~wiregauge(2.3048468 mm) = 11

2.8. Operator precedence

The following table summarizes all operators in the order of precedence.

prefix
concatenated exponent
number division |                   (left to right)
unary + -
exponent ^ **                       (right to left)
multiplication by juxtaposition     (left to right)
multiplication and division * / per (left to right)
sum + -                             (left to right)

A plus and minus is treated as unary only if it comes first in the expression or follows any of the operators ^, **, *, /, per, +, or -. Thus, 5 -2 is interpreted as '5 minus 2', and not as '5 times -2'.

Parentheses can be applied in the usual way to indicate the order of evaluation.

2.9. Exact syntax of expressions

The syntax of expressions is defined as follows. Phrases and symbols in quotes represent themselves, | means 'or', ? means optional occurrence, and * zero or more occurrences.

expr     = term (('+' | '-') term)*
           | ('/' | 'per') product
term     = product (('*' | '/' | 'per') product)*
product  = factor factor*
factor   = unary (('^' | '**') unary)*
unary    = ('+' | '-')? primary
primary  = unitname
           | numexpr
           | bfunc '(' expr ')'
           | '~'? dfunc '(' expr ')'
           | '(' expr ')'
numexpr  = number ('|' number)*
number   = mantissa exponent?
mantissa = '.' digits
           | digits ('.' digits?)?
exponent = ('e' | 'E') sign? digits

unitname = unit name with optional prefix, suffix, and / or one-digit exponent
bfunc    = built-in function name: sqrt, cuberoot, sin, cos, etc.
dfunc    = defined function name

Names of syntactic elements shown above in italics may appear in error messages that you receive if you happen to enter an incorrect expression. For example:

You have: 1|m
After '1|': expected number.

You have: cm^per $
After 'cm^': expected unary.

You have: 3 m+*lbf
After '3 m+': expected term.

Spaces are in principle ignored, but they are often required in multiplication by juxtaposition. For example, writing newtonmeter will result in the message Unit 'newtonmeter' is unknown; you need a space in the product newton meter.

To avoid ambiguity, a space is also required before a number that follows another number. Thus, an error will be indicated after 1.2 in 1.2.3.

Multiplication by juxtaposition may also result in another ambiguity. As e is a small unit of charge, an expression like 3e+2C can be regarded as meaning (3e+2)*C or (3*e)+(2*C). This ambiguity is resolved by always including as much as possible in a number.


3. Specifying what you want

3.1 Unit or expression

In the Overview, it was shown how you specify the result by entering a unit name at You want. In fact, you can enter there any expression specifying a quantity with the same dimension as the expression at You have:

You have: 10 gallons
You want: 20 cm * circlearea(5cm)
  10 gallons = 24.09868 * 20 cm * circlearea(5cm)

This tells you that you can almost fit 10 gallons of liquid into 24 cans of diameter 10 cm and 20 cm tall. However:

You have: 10 gallons
You want: circlearea(5cm)
Conformability error
  10 gallons = 0.037854118 m^3
  circlearea(5cm) = 0.0078539816 m^2

Some units, like radian and steradian, are treated as dimensionless and equal to 1 if it is necessary for conversion. For example, power is equal to torque times angular velocity. The dimension of expression at You have below is kg m^2 radian/s^3, and the dimension of watt is kg m^2/s^3 The computation is made possible by treating radian as dimensionless:

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

Note that dimensionless units are not treated as dimensionless in other contexts. They cannot be used as exponents so for example, meter^radian is not allowed.

3.2 Reciprocal conversion

You can also enter at You want an expression with dimension that is an inverse of that at You have:

You have: 8 liters per 100 km
You want: miles per gallon
  reciprocal conversion
  1 / 8 liters per 100 km = 29.401823 miles per gallon

Here, You have has the dimension of volume divided by length, while the dimension of You want is length divided by volume. This is indicated by the message reciprocal conversion, and by showing the result as equal to the inverse of You have.

3.3 Function inverse

You may enter at You want the name of a function, without argument. This will apply the function's inverse to the quantity from You have:

You have: 30 cm^2
You want: circlearea
  30 cm^2 = circlearea(0.030901936 m)

You have: 300 K
You want: tempF
  300 K = tempF(80.33)
Of course, You have must specify the correct dimension:
You have: 30 cm
You want: circlearea
  Argument 0.3 m of function ~circlearea is not conformable to 1 m^2.

3.4 Reduce to primitive units

If you leave You want field empty, you obtain the quantity from You have reduced to primitive units:

You have: 7 mph
You want:
  3.12928 m / s

3.5 Mixed units

For conversion to a sum of units, you enter at You want a list of units separated by semicolons:
You have: 2 m
You want: ft;in;1|8 in
  2 m = 6 ft + 6 in + 5.9212598 * 1|8 in
Note that you are not limited to unit names, but can use expressions like 1|8 in above. The first unit is subtracted from the given value as many times as possible, then the second from the rest, and so on; finally the rest is converted exactly to the last unit in the list.

Ending the unit list with ';' separates the integer and fractional parts of the last coefficient:

You have: 2 m
You want: ft;in;1|8 in;
  2 m = 6 ft + 6 in + 5|8 in + 0.9212598 * 1|8 in
Ending the unit list with ';;' results in rounding the last coefficient to an integer:
You have: 2 m
You want: ft;in;1|8 in;;
  2 m = 6 ft + 6 in + 6|8 in (rounded up to nearest 1|8 in)
Each unit on the list must be conformable with the first one on the list, and with the one you entered at You have:
You have: meter
You want: ft;kg
Invalid unit list. Conformability error:
  ft = 0.3048 m
  kg = 1 kg

You have: meter
You want: lb;oz
Conformability error
  meter = m
  lb = 0.45359237 kg
Of course you should list the units in a decreasing order; otherwise, the result may not be very useful:
You have: 3 kg
You want: oz;lb
  3 kg = 105 oz + 0.051367866 lb
A unit list such as
cup;1|2 cup;1|3 cup;1|4 cup;tbsp;tsp;1|2 tsp;1|4 tsp
can be tedious to enter. Units provides shorthand names for some common combinations:
hms     hours, minutes, seconds
dms     angle: degrees, minutes, seconds
time    years, days, hours, minutes and seconds
usvol   US cooking volume: cups and smaller
Using these shorthands, or unit list aliases, you can do the following conversions:
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
You cannot combine a unit list alias with other units: it must appear alone at You want.


4. Nonlinear measures

Some measures cannot be expressed as the product of a number and a measurement unit. Such measures are called nonlinear.

An example of nonlinear measure is the pH value used to express the concentration of certain substance in a solution. It is a negative logarithmic measure: a tenfold increase of concentration decreases the pH value by one. You convert between pH values and concentration using the function pH mentioned under Functions:

You have: pH(6)
You want: micromol/gallon
  pH(6) = 3.7854118 micromol/gallon

For conversion in the opposite direction, you use the inverse of pH, as described under Specifying result:

You have: 0.17 micromol/cm^3
You want: pH
  0.17 micromol/cm^3 = pH(3.7695511)

Other example of nonlinear measures are different "gauges". They express the thickness of a wire, plate, or screw, by a number that is not obviously related to the familiar units of length. (Use the Search button on gauge to find them all.) Again, they are handled by functions that convert the gauge to units of length:

You have: wiregauge(11)
You want: inches
  wiregauge(11) = 0.090742002 inches

You have: 1mm
You want: wiregauge
  1mm = wiregauge(18.201919)

The most common example of nonlinear measure is the temperature indicated by a thermometer, or absolute temperature: you cannot really say that it becomes two times warmer when the thermometer goes from 20°F to 40°F. Absolute temperature is expressed relative to an origin; such measure is called affine. To handle absolute temperatures, Units provides functions such as tempC and tempF that convert them to degrees Kelvin. (Other temp functions can be found using the Search button.) The following shows how you use these functions to convert absolute temperatures:

You have: tempC(36)
You want: tempF
  tempC(36) = tempF(96.8)

meaning that 36°C on a thermometer is the same as 96.8°F.

You can think of pH(6), wiregauge(11), tempC(36), or tempF(96.8) not as functions but as readings on the scale pH, tempC, or tempF, used to measure some physical quantity. You can read the examples above as: 'what is 0.17 micromol/cm^3 on the pH scale?', or 'what is 1 mm on the wiregauge scale?', or 'what is the tempF reading corresponding to 36 on tempC scale?'

Note that absolute temperature is not the same as temperature difference, in spite of their units having the same names. The latter is a linear quantity. Degrees Celsius and degrees Fahrenheit for measuring temperature difference are defined as linear units degC and degF. They are converted to each other in the usual way:

You have: 36 degC
You want: degF
  36 degC = 64.8 degF

 


5. Localization

Some units have different values in different locations. The localization feature accomodates this by allowing the units database to specify region-dependent definitions.

In the database, the US units that differ from their British counterparts have names starting with us: uston, usgallon, etc.. The corresponding British units are: brton, brgallon, etc.. When using Units, you have a possibility to specify en_US or en_GB as 'locale'. Each of them activates a portion of the database that defines short aliases for these names. Thus, specifying en_US as locale activates these aliases:

ton     =  uston
gallon  =  usgallon
etc.
while en_GB activates these:
ton     =  brton
gallon  =  brgallon
etc.

You can specify locale in the property list or in a command option.

The US Survey foot, yard, and mile can be obtained by using the US prefix. These units differ slightly from the international length units. They were in general use until 1959, and are still used for geographic surveys. The acre is officially defined in terms of the US Survey foot. If you want an acre defined according to the international foot, use intacre. The difference between these units is about 4 parts per million. The British also used a slightly different length measure before 1959. These can be obtained with the prefix UK.


6. Adding own unit definitions

The units data base is defined by a units data file. A default units file, called units.dat, is packaged in the JAR file together with the program. (You can extract it from there using the jar tool of Java.)

If you want to add your own units, you can write your own units file. See how to do it under Writing units file. If you place that file in your home directory under the name units.dat, it will be read after the default units file.

You may also supply one or more own unit files and access them using the property list or command option. In each case, you specify the order in which Units will read them. If a unit with the same name is defined more than once, Units will use the last definition that it encounters.


7. Command interface

If you want, you may run Units from command line. It imitates then almost exactly the behavior of GNU Units. (The differences are listed under What is different.)

To use the command line interface, you need to download the Java archive (JAR) file that contains the executable classes and the data file. You can save the JAR in any directory of your choice, and give it any name compatible with your file system. The following assumes that you saved the JAR file under the name jarfile. It also assumes that you have a Java Runtime Environment (JRE) version 1.5.0 or later that is invoked by typing java at your shell prompt.

7.1. Interactive use

To use Units in the interactive mode, type:
    java -jar jarfile -i
or
    java -jar jarfile options

at your shell prompt. The program will print something like this:

2192 units, 71 prefixes, 32 nonlinear units
You have:

At You have prompt, type the expression you want to evaluate. Next, Units will print You want. There you tell how you want your result, in the same way as in the graphical interface. See under Expressions and Specifying result. As an example, suppose you just want to convert ten meters to feet. Your dialog will look like this:

You have: 10 meters
You want: feet
  * 32.8084
  / 0.03048

The answer is displayed in two ways. The first line, which is marked with a * to indicate multiplication, says that the quantity at You have is 32.8084 times the quantity at You want. The second line, marked with a / to indicate division, gives the inverse of that number. In this case, it tells you that 1 foot is equal to about 0.03 dekameters (dekameter = 10 meters). It also tells you that 1/32.8 is about .03.

Units prints the inverse because sometimes it is a more convenient number. For example, if you try to convert grains to pounds, you will see the following:

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

From the second line of the output you can immediately see that a grain is equal to a seven thousandth of a pound. This is not so obvious from the first line of the output.

If you find the output format confusing, try using the -v ('verbose') option, which gives:

You have: 10 meters
You want: feet
  10 meters = 32.8084 feet
  10 meters = (1 / 0.03048) feet

You can suppress printing of the inverse using the -1 ('one line') option. Using both -v and -1 produces the same output as the graphical interface:

You have: 5 yards * (4 feet + 3 in) * 7 in * 1 kg/liter
You want: pounds
  5 yards * (4 feet + 3 in) * 7 in * 1 kg/liter = 2321.5398 pounds

If you request a conversion between units which measure reciprocal dimensions, Units will display the conversion results with an extra note indicating that reciprocal conversion has been done:

You have: 6 ohms
You want: siemens
  reciprocal conversion
  * 0.16666667
  / 6
Again, you may use the -v option to get more comprehensible output:
You have: 6 ohms
You want: siemens
  reciprocal conversion
  1 / 6 ohms = 0.16666667 siemens
  1 / 6 ohms = (1 / 6) siemens

When you specify compact output with -c, you obtain only the conversion factors, without indentation:

You have: meter
You want: yard
1.0936133
0.9144

When you specify compact output and perform conversion to mixed units, you obtain only the conversion factors separated by semicolons. Note that unlike the case of regular output, zeros are included in this output list:

You have: meter
You want: yard;ft;in
1;0;3.3700787

If you only want to find the reduced form or definition of a unit, simply press return at You want prompt. For example:

You have: 7 mph
You want:
  3.12928 m/s

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

The definition is shown if you entered a unit name at You have prompt. The example indicates that jansky is defined as equal to fluxunit which in turn is defined to be a certain combination of watts, meters, and hertz. The fully reduced form appears on the far right.

If you type ? at You want prompt, the program will display a list of named units which are conformable with the unit that you entered at You have prompt. Note that conformable unit combinations will not appear on this list.

Typing help at either prompt displays a short help message. You can also type help followed by a unit name. This opens a window on the units file at the point where that unit is defined. You can read the definition and comments that may give more details or historical information about the unit.

Typing search followed by some text at either prompt displays a list of all units whose names contain that text as a substring, along with their definitions. This may help in the case where you aren't sure of the right unit name.

To end the session, you type quit at either prompt, or press the Enter (Return) key at You have prompt.

7.2. Non-interactive use

You can use Units to perform computations non-interactively from the command line. To do this, type

    java -jar jarfile [options] you-have [you-want]

at your shell prompt. (You will usually need quotes to protect the expressions from interpretation by the shell.) For example, if you type

java -jar jarfile "2 liters" "quarts"
the program will print
  * 2.1133764
  / 0.47317647
and then exit.

If you omit you-want, Units will print out definition of the specified unit.

7.3. Options

The following options allow you to use alternative units file(s), check your units file, or change the output format:

-C
Check that all units and prefixes defined in the units data file reduce to primitive units. Print a list of all units that cannot be reduced. Also display some other diagnostics about suspicious definitions in the units data file. Note that only definitions active in the current locale are checked. This option may be specified with -v to help find unit definitions that cause endless loops. Any other options and arguments are ignored.
-c
compact: give compact output featuring only the conversion factor(s). This option overrides the -v option.
-e
charset
Assume that input and output in the interactive mode is encoded using the character set named charset. It must be one of the character sets available at your Java installation. See Unicode support for more detail.
-f
filename
Load the units file filename. You should specify full path as filename.
Empty string as filename (-f "") means the units.dat file supplied with the program. This enables you to use the supplied file plus a personal units file. Up to 25 units files may be specified on the command line. The files will be read in the order they appear in the command.
-g
fontname
Use font fontname in the window diplayed in response to help, ?, and search. It must be one of the fonts available at your Java installation. See Unicode support for more detail.
-h
help: print out a summary of the options for Units.
-i
interactive: use interactive prompts (rather than graphic interface).
-l
locale
Use the specified locale. If locale is not specified in this way, Units uses en_US. It does not attempt to obtain locale from the system.
-q
quiet: suppress prompting of the user for units and the display of statistics about the number of units loaded.
-r
round: in conversion to a sum of units, round the last term of the result to an integer. Overrides a semicolon appearing at the end of unit list.
-s
strict: suppress conversion of units to their reciprocal units. For example, Units will normally convert hertz to seconds because these 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 attempt to convert hertz to seconds.
-1
one-line: give only one line of output (the forward conversion). Do not print the reverse conversion. Note that if Units performs a reciprocal conversion, it will still print the "reciprocal conversion" line.
-t
terse: give terse output. This option can be used when calling Units from another program so that the output is easy to parse. It is equivalent to specifying -csq1.
-v
verbose: give slightly more verbose output.
-V
Print program version number.

7.4. What is different in Java version

The Java imitation is not an exact port of the original GNU units. The following is a (most likely incomplete) list of differences.


8. Properties

You can supply some parameters to Units by setting up a Property list. It is a file named units.opt, placed in the same directory as the JAR file. It may look like this:

GUIFONT = Lucida
ENCODING = Cp850
LOCALE = en_GB
UNITSFILE = ; c:\\Java\\gnu\\units\\my.dat

The options -e, -f, -g, and -l specified on the command line override settings from the Property list.


9. Setting up an applet

Starting with release 1.7.0_51, Java blocks unsigned applets. For this reason, you can no longer embed Units as an applet in your web page.


10. Writing units file

The units data base is defined by a units data file. A default units file, called units.dat, is packaged in the JAR file together with the program. This section tells you how to write your own units file that you can use together with, or instead of, the default file, as described under Adding own units.

10.1. Overall structure

The file has to use the UTF-8 character encoding. Since the ASCII characters appear the same in all encodings, you do not need to worry about UTF-8 as long as your definitions use only these characters.

Each definition occupies one line, possibly continued by the backslash character (\) that appears as the last character.

A line starting with ! is a command. See Defining locale and Including file. Non-command lines may start with white space (blanks or tab characters).

Comments start with a # character, which can appear anywhere in a line. Following #, the comment extends to the end of the line.

Empty lines are ignored.

10.2. Units and prefixes

A unit is specified on a single line by giving its name followed by at least one blank, followed by the definition.

A unit name must not contain any of the characters + - * / | ^ ( ) ; #. It cannot begin with a digit, underscore, tilde, decimal point, or comma. It cannot end with an underscore, decimal point, or comma.

If a name ends in a digit other than zero or one, the digit must be preceded by a string beginning with an underscore, and afterwards consisting only of digits, decimal points, or commas. For example, NO_2, foo_2,1 or foo_3.14 would be valid names but foo2 or foo_a2 would be invalid.

The definition is either an expression, defining the unit in terms of other units, or ! indicating a primitive unit, or !dimensionless indicating a dimensionless primitive unit.

Be careful to define new units in terms of old ones so that a reduction leads to the primitive units. You can check this using the -C option. See under Checking your definitions.

Here is an example of a short units 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    0.0254 m        # Inch defined in terms of meters
ft      12 inches       # The foot defined in terms of inches
mile    5280 ft         # And the mile

A unit which 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.

10.3. Computed functions

Here is an example of function definition:

tempF(x) [1;K] (x+(-32)) degF + stdtemp ; (tempF+(-stdtemp))/degF + 32

The definition begins with the function name followed immediately (with no spaces) by the name of the parameter in parentheses. Both names must follow the same rules as unit names.

Next, in brackets, is a specification of the units required as arguments by the function and its inverse. In the example above, the tempF function requires an input argument conformable with 1. The inverse function requires an input argument conformable with K. Note that this is also the dimension of function's result.

Next come the expressions to compute the function and its inverse, separated by a semicolon. In the example above, the tempF function is computed as

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

The inverse has the name of the function as its parameter. In our example, the inverse is

~tempF(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, but then conversions to the unit will be impossible.

If you wish to make synonyms for nonlinear units, you still need to define both the forward and inverse functions. So to create a synonym for tempF you could write

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

The example below is a function to compute the area of a circle. Note that this definition requires a length as input and produces an area as output, as indicated by the specification in brackets.

circlearea(r) [m;m^2] pi r^2 ; sqrt(circlearea/pi)

Empty or omitted argument specification means that Units will not check dimension of the argument you supply. Anything compatible with the specified computation will work. For example:

square(x) x^2 ; sqrt(square)
square(5) = 25
square(2m) = 4 m^2

10.4. Tabular functions (piecewise linear functions)

Some functions cannot be computed using an expression. You have then a possibility to define such a function by a piecewise linear approximation. You provide a table that lists values of the function for selected values of the argument. The values for other arguments are computed by linear interpolation.

An example of piecewise linear function 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 function. The unit in square brackets applies to the result. Tha argument is always a number. No spaces can appear before the ] character, so a definition like foo[kg meters] is illegal; instead write foo[kg*meters].

The definition is a list of pairs optionally separated by commas. Each pair defines the value of the function at one point. 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, you define zincgauge at five points. We have thus zincgauge(1) = 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

If you define a piecewise linear function that is not strictly monotone, the inverse will not be well defined. In such a case, Units will return the smallest inverse.

10.5. 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

Unit list aliases are only for unit lists, so the definition must include a ';'. Unit list aliases can never be combined with units or other unit list aliases, so the definition of time shown above could not have been shortened to year;day;hms. As usual, be sure to run Units with option -C to ensure that the units listed in unit list aliases are conformable.

10.6. Defining Locale

A locale region in the units file begins with !locale followed by the name of the locale. The locale region is terminated by !endlocale. The following example shows how to define a couple of units in a locale.

!locale en_GB
ton              brton
gallon           brgallon
!endlocale

10.7. Including files

A file can be included by giving the command !include followed by full path to the file.

10.8. Checking your definitions

You are recommended to check the new or modified units file by invoking Units from command line with option -C. Of course, the file must be made available to Units as described under Adding own units.

The option will check that the definitions are correct, and that all units reduce to primitive ones. If you created a loop in the units definitions, Units will hang when invoked with the -C option. You will need to use the combined -Cv option which prints out each unit as it checks them. The program will still hang, but the last unit printed will be the unit which caused the infinite loop.

If the inverse of a function is omitted, the -C option will display a warning. It is up to you to calculate and enter the correct inverse function to obtain proper conversions. The -C 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.

The -C option will print a warning if a non-monotone piecewise linear function is encountered.


11. Unicode support

Units works internally with double-byte Unicode characters.

The unit data files use the UTF-8 encoding. This enables you to use Unicode characters in unit names. However, you can not always access them.

The graphical interface of Units can display all characters available in its font. Those not available are shown as empty rectangles. The default font is Monospaced. It is a so-called logical font, or a font family, with different versions depending on the locale. It usually contains all the national characters and much more, but far from all of Unicode. You may specify another font by using the property GUIFONT, or the command option -g.

You can enter into the Units window all chracters available at your keyboard, but there is no facility to enter any other Unicode characters.

The treatment of Unicode characters at the command interface depends on the operating system and the Java installation. The operating system may use character encoding different from the default set up for Java Virtual Machine (JVM). As the result, names such as ångström typed in the command window are not recognized as unit names. If you encounter this problem, and know the encoding used by the system, you can identify the encoding to Units with the help of the property ENCODING or command option -e. (In Windows XP, you can find the encoding using the command chcp. In one case investigated by the author, the encoding was Cp437, while the JVM default was Cp1252.)

The units.dat file supplied with Units contains commands !utf8 and !endutf8. This is so because it is taken unchanged from GNU units. The commands enclose the portions of file that use non-ASCII characters so they can be skipped in environments that do not support UTF-8. Because Java always supports the UTF-8 encoding for input files, the commands are ignored in Units.


12. License and copyright

The program documented here is a Java development of GNU Units 1.89e, a program written in C by Adrian Mariano (adrian@cam.cornell.edu). The file units.dat containing the units data base was created by Adrian Mariano, and is maintained by him. The package contains the latest version obtained from GNU Units repository.

GNU Units copyright © 1996, 1997, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2010, 2011 by Free Software Foundation, Inc. Java version copyright © 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012 by Roman Redziejowski.

The program is free software: you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

The program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

This Web page copyright © 2012 by Roman Redziejowski. The author gives unlimited permission to copy, translate and/or distribute it document, with or without modifications, as long as this notice is preserved, and information is provided about any changes.

Substantial parts of this text have been taken, directly or modified, from the manual Unit Conversion, edition 1.89g, written by Adrian Mariano, copyright © 1996, 1997, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2011 by Free Software Foundation, Inc., under a written prmission contained in that document.