Engineering Unit Converter: Code Examples

Convert between units of length, mass, temperature, pressure, speed, and more.

ZERO UPLOAD · ALL LOCAL
  1. Pick a physical dimension from the category bar below.
  2. Type a value into any unit field — all other units update instantly.
  3. Tap Copy next to any field to grab that converted value.
Millimetre mm
Centimetre cm
Metre m
Kilometre km
Inch in
Foot ft
Yard yd
Mile mi
Nautical Mile nmi

INFO Length measures distance in space. The SI unit is the metre, defined since 2019 as the distance light travels in 1/299,792,458 of a second.

The metre was first defined by the French Academy of Sciences in 1793 as one ten-millionth of the distance from the North Pole to the equator along a meridian.

Milligram mg
Gram g
Kilogram kg
Tonne t
Pound lb
Ounce oz
Stone stone
Slug slug

INFO Mass measures the amount of matter in an object. The SI unit is the kilogram, the only SI base unit still named with a prefix.

The kilogram was defined by the International Prototype Kilogram, a platinum-iridium cylinder kept in Paris, from 1889 until 2019 when it was redefined in terms of Planck's constant.

Kelvin K
Celsius °C
Fahrenheit °F
Rankine °R

INFO Temperature describes the thermal energy state of matter. The SI unit is the kelvin, an absolute scale where zero represents the complete absence of thermal motion.

The kelvin scale was proposed by William Thomson (Lord Kelvin) in 1848, based on his calculation that absolute zero lies at roughly −273 degrees Celsius.

Square Millimetre mm²
Square Centimetre cm²
Square Metre
Square Kilometre km²
Square Inch in²
Square Foot ft²
Acre ac
Hectare ha

INFO Area measures the extent of a two-dimensional surface. The SI unit is the square metre, derived directly from the metre.

Land area measurement is one of the oldest applications of geometry. The acre traces back to the amount of land an ox could plough in a day in medieval England.

Millilitre mL
Litre L
Cubic Metre
Cubic Inch in³
Cubic Foot ft³
Fluid Ounce (US) fl oz
Pint (US) pt
Quart (US) qt
Gallon (US) gal (US)
Gallon (UK) gal (UK)

INFO Volume measures the three-dimensional space occupied by an object or substance. The litre, equal to one cubic decimetre, is the practical standard for liquids and gases.

The litre was introduced as part of the French Revolutionary metric system in 1795, defined as the volume of one kilogram of water at 4 degrees Celsius.

Millisecond ms
Second s
Minute min
Hour h
Day day
Week week

INFO Time measures the sequence and duration of events. The SI unit is the second, defined since 1967 by the oscillations of a caesium-133 atom.

The division of time into 60 seconds per minute and 60 minutes per hour comes from the Babylonian base-60 number system, used at least as far back as 2000 BCE.

Pascal Pa
Kilopascal kPa
Megapascal MPa
Bar bar
Millibar mbar
PSI psi
Atmosphere atm
Torr torr
mmHg mmHg

INFO Pressure is the force applied perpendicular to a surface divided by the area over which it acts. The SI unit is the pascal, equal to one newton per square metre.

Blaise Pascal demonstrated in 1648 that atmospheric pressure decreases with altitude by having his brother-in-law carry a mercury barometer up a mountain.

Newton N
Kilonewton kN
Meganewton MN
Pound-force lbf
Kilogram-force kgf
Dyne dyn

INFO Force is any interaction that causes a mass to accelerate. The SI unit is the newton, defined as the force needed to accelerate one kilogram at one metre per second squared.

The newton was named for Isaac Newton, whose second law of motion (F = ma), published in Principia Mathematica in 1687, first formalised the relationship between force, mass, and acceleration.

Newton-millimetre N·mm
Newton-centimetre N·cm
Newton-metre N·m
Kilonewton-metre kN·m
Pound-force inch lbf·in
Pound-force foot lbf·ft

INFO Torque is the tendency of a force to rotate an object about an axis. The SI unit is the newton-metre, equal to a one-newton force applied one metre from the pivot.

The principle behind torque was described by Archimedes around 250 BCE in his work on levers: the longer the lever arm, the less force needed to lift a load.

Joule J
Kilojoule kJ
Megajoule MJ
Kilowatt-hour kWh
Calorie cal
Kilocalorie kcal
BTU BTU
Electronvolt eV

INFO Energy is the capacity to do work or transfer heat. The SI unit is the joule, defined as the work done when a one-newton force moves an object one metre.

James Prescott Joule established the mechanical equivalent of heat between 1843 and 1850, showing that mechanical work and heat are both forms of energy that can convert into each other.

Milliwatt mW
Watt W
Kilowatt kW
Megawatt MW
Horsepower (mech) hp
BTU per hour BTU/h

INFO Power is the rate at which energy is transferred or work is done. The SI unit is the watt, equal to one joule per second.

The watt was named for James Watt, who improved steam engine efficiency in the 1760s and coined horsepower as a practical unit for comparing engine output to horse labour.

Metre per second m/s
Kilometre per hour km/h
Miles per hour mph
Foot per second ft/s
Knot kn

INFO Speed is the rate of change of position. The SI unit is metres per second; kilometres per hour and miles per hour are the everyday standards.

The first accurate measurement of the speed of light was made by Ole Romer in 1676 by observing timing shifts in the moons of Jupiter as Earth moved toward and away from them.

Metre per second squared m/s²
Centimetre per second squared cm/s²
Foot per second squared ft/s²
Standard gravity g₀

INFO Acceleration is the rate of change of velocity, measured in metres per second squared. Standard gravity (g₀ = 9.80665 m/s²) is a reference value in engineering and navigation.

Galileo Galilei measured gravitational acceleration in the 1590s by rolling balls down inclined planes, disproving the Aristotelian claim that heavier objects fall faster.

Kilogram per cubic metre kg/m³
Gram per cubic centimetre g/cm³
Gram per litre g/L
Pound per cubic foot lb/ft³
Pound per cubic inch lb/in³

INFO Density is the mass of a substance divided by the volume it occupies. The SI unit is kilogram per cubic metre; grams per cubic centimetre is common in materials science.

Archimedes reportedly discovered the principle of displacement while stepping into a full bath around 250 BCE, giving him a way to measure the volume of irregular objects.

Radian rad
Degree deg
Gradian grad
Arcminute arcmin
Arcsecond arcsec
Turn turn

INFO An angle measures the amount of rotation between two rays from a common point. The SI unit is the radian, defined as the angle subtended by an arc equal in length to the circle's radius.

The term "radian" was coined by mathematician Roger Cotes around 1714, though the concept had been used implicitly in earlier work by Euler and others.

Litres per 100 km L/100km
Kilometres per litre km/L
MPG (US) mpg (US)
MPG (UK) mpg (UK)

INFO Fuel consumption measures how much fuel a vehicle uses over a given distance. Europe expresses this as litres per 100 kilometres (lower is better); the US and UK use miles per gallon (higher is better).

The L/100 km standard gained wide adoption after the 1973 oil crisis prompted governments to standardise fuel economy labelling and set targets for car manufacturers.

Pascal-second Pa·s
Millipascal-second mPa·s
Centipoise cP
Poise P

INFO Dynamic viscosity measures a fluid's internal resistance to flow. The SI unit is the pascal-second; the centipoise (cP) is common in industry, with water at 20 °C measuring about 1 cP.

Jean Louis Marie Poiseuille established the laws of viscous flow in 1838 while studying blood circulation in capillaries, and the poise unit was named in his honour.

Unit Conversion in Python with Pint

Pint is a Python library that lets you define quantities with units and convert between them using a familiar syntax1. It integrates with NumPy and supports dimensional analysis, raising DimensionalityError on incompatible conversions. The library ships with a comprehensive database of SI, imperial, and US customary units.

Setting up pint and working with the UnitRegistry

Inside a pint workflow, every value passes through a UnitRegistry before any conversion happens, and you create one instance per application then share it across all modules because creating multiple registries causes unit incompatibility errors when values from different registries interact, which is a pitfall that catches many first-time pint users who create a new registry in each module without realising the values become incompatible2.

Attaching units: multiplication versus the Quantity constructor

Once the registry exists, you attach a unit to a number either through multiplication or through the Quantity constructor, and the multiplication form is the shorter path for most numeric types, though for absolute temperatures it treats the value as a difference rather than a fixed point and produces incorrect results that skip the constant offset. Use ureg.Quantity(100, ureg.degC) for any absolute temperature conversion so pint applies the full formula including the constant offset. pint ships with the complete SI unit system, and non-SI units are included too: imperial, US customary, and CGS units all work out of the box.

Converting between units and extracting raw values

Converting a pint Quantity uses the .to() method, which returns a new Quantity in the requested unit without modifying the original, and calling dist.to(ureg.mile) on a 5-kilometre Quantity returns a new object holding the value in miles while leaving the original Quantity unchanged so you can convert it again to a different unit without reconstructing it from scratch3. To extract the underlying number, call .magnitude on the result, and .units returns a string representation of the current unit.

Working with NumPy arrays through pint

pint integrates with NumPy without any additional configuration, wrapping a NumPy array to give you a Quantity that preserves units across vectorized operations without any manual looping, which means arr = np.array([1.0, 2.0, 3.0]) * ureg.kilometre converts the entire array with a single arr.to(ureg.mile) call rather than iterating element by element. Standard NumPy ufuncs including np.sqrt, np.mean, and np.sum propagate units correctly through the operation. Building on this, .to_base_units() simplifies any Quantity to SI base units, which normalizes values before database storage or comparison across unit families, while .to_reduced_units() goes further and simplifies compound units to their irreducible form by combining numerator and denominator dimensions where possible.

When DimensionalityError appears and how to define custom units

When pint encounters an incompatible conversion, it raises pint.DimensionalityError immediately rather than returning a wrong number silently, and catching this exception explicitly when processing user-supplied unit strings is the key to building a robust application that returns a validation error rather than crashing4. Converting kilometres to kilograms throws because length and mass share no dimensional relationship. Catch this exception explicitly when processing user-supplied unit strings from a form or external API; wrap the .to() call in a try/except block and return a validation error rather than letting the exception propagate.

Registering application-specific units

For engineering domains with non-standard units, ureg.define() extends the registry at runtime. The format is a plain string: ureg.define('furlong = 201.168 m') registers a new unit that participates in all conversions and arithmetic contexts. You can also define dimensionless ratios: ureg.define('ppm = 1e-6') registers parts-per-million as a conversion-ready unit. Add custom definitions once during application startup, before the registry is shared across modules. Defining the same unit a second time raises pint.errors.RedefinitionError, so guard the definition call if your startup sequence might execute more than once in the same process.

Building on these startup concerns, web application contexts using FastAPI, Flask, or Django call for careful initialization: create the UnitRegistry once at module level and import it from a shared utilities module. pint's UnitRegistry is thread-safe for read operations including lookups and conversions; it modifies internal state only during ureg.define() calls. Thread safety comes built in. Consequently, you can share one registry instance across concurrent requests without adding lock primitives around conversion calls. Avoid reconstructing the registry per request: loading the default unit definition file takes several milliseconds and adds overhead that compounds under high load. If your application defines custom units, guard the definition call with a module-level boolean flag, since Django's development auto-reloader can trigger module initialization code twice in the same process5.

Notes

Install with pip install pint. You attach units to values via UnitRegistry. Conversion uses .to(). For absolute temperatures, use ureg.Quantity(value, ureg.degC); the multiplication form treats temperature as a difference and skips the offset.

Examples

Basic conversion

import pint
ureg = pint.UnitRegistry()
dist = 5 * ureg.kilometre
print(dist.to(ureg.mile))
# 3.1068559611866697 mile

Temperature (absolute)

temp = ureg.Quantity(100, ureg.degC)
print(temp.to(ureg.degF))
# 212.0 degF

Use Quantity() for temperatures; value * ureg.degC treats it as a difference.

Verify with the Engineering Unit Converter tool.

Basic conversion

import pint
ureg = pint.UnitRegistry()
dist = 5 * ureg.kilometre
print(dist.to(ureg.mile))
# 3.1068559611866697 mile

Code says: 3.1068559611866697 mile

Temperature (absolute)

temp = ureg.Quantity(100, ureg.degC)
print(temp.to(ureg.degF))
# 212.0 degF

Use Quantity() for temperatures; value * ureg.degC treats it as a difference.

Code says: 212.0 degF

Pint conversion reference

  • 3.1068559611866697 mi
  • 212.0 °F
  • 1 furlong = 201.168 m

Use ureg.Quantity(value, ureg.degC) for absolute temperatures — the multiplication form (value * ureg.degC) skips the offset.

Sources
  1. 1.

    "Tutorial," Pint, pint.readthedocs.io, accessed June 2026. https://pint.readthedocs.io/en/stable/getting/tutorial.html

  2. 2.

    "Using Pint in your projects," Pint, pint.readthedocs.io, accessed June 2026. https://pint.readthedocs.io/en/stable/getting/pint-in-your-projects.html

  3. 3.

    "Furlong," Wikipedia, accessed June 2026. https://en.wikipedia.org/wiki/Furlong

  4. 4.

    "Dimensional analysis," Wikipedia, accessed June 2026. https://en.wikipedia.org/wiki/Dimensional_analysis

  5. 5.

    "Universal functions (ufunc)," NumPy, numpy.org, accessed June 2026. https://numpy.org/doc/stable/reference/ufuncs.html

FAQ

Unit Conversion in JavaScript with convert-units

Convert-units is an npm package with a chainable API for converting between common unit pairs1. It covers length, mass, temperature, volume, and more with built-in TypeScript types and zero runtime dependencies. The package works in Node.js, browsers, Deno, and React Native without modification.

Setting up convert-units and exploring the chainable API

Installing convert-units requires a single npm command: npm install convert-units2. The package ships with both CommonJS and ESM builds, so const convert = require('convert-units') and import convert from 'convert-units' both work depending on your project's module system. Once imported, you build a conversion with a three-part chain: .from() declares the source unit, .to() specifies the target, and the result is a plain number. The library covers length, mass, temperature, volume, and several other measurement categories out of the box.

Discovering valid units with possibilities() and describe()

Before converting, you can discover which target units are valid for a given source with .possibilities(), which returns an array of every unit string the library can convert from your specified source unit. Calling convert().from('km').possibilities() returns an array of every unit string convertible from kilometres. For human-readable labels, .describe() on a unit string returns an object with singular, plural, and abbr fields. Use convert().from('km').possibilities().map(u => convert().describe(u)) to generate a labeled dropdown of unit options without hardcoding any unit strings into your UI, which keeps the interface maintainable when new units are added in a library update.

A practical use is a unit picker that rebuilds its options whenever the dependency updates, so the displayed list never drifts out of sync with the installed version. Generating those labels at runtime also removes a failure mode where a typo in a hardcoded unit string would silently break the selector, because the labels now come from the library itself rather than from a hand-maintained list that someone has to remember to edit.

When convert-units throws and how to validate unit strings at runtime

When you pass an unrecognized unit string to .from() or .to(), convert-units throws an error immediately rather than returning undefined or an incorrect value3. The error message names the invalid unit, which makes debugging straightforward. If your application accepts unit strings from user input or an external API, wrap each conversion in a try/catch block and use .possibilities() to pre-validate before converting.

Runtime validation and TypeScript type predicates

The runtime validation pattern is: check whether the user-supplied unit appears in convert().possibilities(), and only call .from(unit).to(targetUnit) if the check passes. TypeScript users get an additional compile-time layer on top of this, since the .from() and .to() arguments are typed as union literals of every valid unit string, so passing an unknown string is a type error caught by the compiler before the code runs. For cross-dimensional errors such as attempting to convert kilometres to kilograms, convert-units also throws because those unit pairs share no measurement category. A type predicate recovers the static guarantee: define a function that tests whether the input appears in convert().possibilities() and annotates the return type as s is Unit, then use it as a runtime guard before the conversion call.

In React, Next.js, and edge runtime environments

In a browser bundle, convert-units adds approximately 20 kB to your final output after minification. Modern bundlers (webpack, Rollup, Vite) cannot tree-shake individual unit definitions because there is no way to know at build time which units your code will request at runtime. For weight-sensitive browser bundles, measure the impact with your bundler's bundle analysis tool before adding the dependency, and consider whether a smaller hand-written conversion table covers your specific unit pairs, since a lookup table for just the five or six conversions your app actually needs can weigh a fraction of the full library.

Server components and edge runtimes

convert-units works without modification in Node.js, Deno, Bun, and Cloudflare Workers because it has zero dependencies and makes no platform assumptions4. In React Server Components and Next.js API routes, import and call it identically to any Node.js module. For Cloudflare Workers, the package operates correctly under the V8 isolate model because it performs no I/O and relies on no browser or Node-specific globals. React Native is also supported. The package contains no DOM or filesystem dependencies, making it portable to any JavaScript runtime5, and CapyToolkit applies the same zero-dependency philosophy to its own browser-based conversion engine, loading every unit definition locally so the conversion never depends on a network round trip.

Notes

Install with npm install convert-units. You build conversions by chaining .from(sourceUnit).to(targetUnit). Call .possibilities() to list valid destination units for a given source. The package works in Node.js, browsers, and React Native with no additional configuration.

Examples

Basic usage

import convert from 'convert-units';
convert(5).from('km').to('mi');
// 3.1068559611866697

List possibilities

convert().from('km').possibilities();
// ['m', 'km', 'cm', 'mm', 'mi', 'ft', 'in', ...]

Temperature

convert(100).from('C').to('F');
// 212

Verify with the Engineering Unit Converter tool.

Basic usage

import convert from 'convert-units';
convert(5).from('km').to('mi');
// 3.1068559611866697

Code says: 3.1068559611866697

Temperature

convert(100).from('C').to('F');
// 212

Code says: 212

convert-units reference

  • 3.1068559611866697
  • 212
  • ~20 kB minified

convert-units throws immediately on an unrecognized unit string rather than returning undefined.

Sources
  1. 1.

    "convert-units," GitHub, github.com, accessed June 2026. https://github.com/convert-units/convert-units

  2. 2.

    "convert-units," npm, npmjs.com, accessed June 2026. https://npmjs.com/package/convert-units

  3. 3.

    "convert-units," GitHub, github.com, accessed June 2026. https://raw.githubusercontent.com/convert-units/convert-units/main/README.md

  4. 4.

    "Npm (software)," Wikipedia, accessed June 2026. https://en.wikipedia.org/wiki/Npm_(software)

  5. 5.

    "Package management basics," MDN Web Docs, developer.mozilla.org, accessed June 2026. https://developer.mozilla.org/en-US/docs/Learn_web_development/Extensions/Client-side_tools/Package_management

FAQ

Unit Conversion in Excel with CONVERT()

Excel's built-in CONVERT() function converts a number from one measurement unit to another without add-ins or macros. It covers distance, mass, time, temperature, pressure, energy, and power.1 The function accepts short unit codes as strings and returns the converted value as a number.

When CONVERT() returns #N/A and how to diagnose it

When Excel's CONVERT() function receives an unrecognized unit code or a dimensionally incompatible pair, it returns #N/A rather than a number. Three situations reliably trigger this error: using 'lb' instead of the correct code 'lbm' for pound-mass, passing a misspelled or empty string, and requesting a conversion between incompatible dimensions such as =CONVERT(5, "km", "kg"). Wrapping CONVERT() in IFERROR() handles all three cases cleanly: =IFERROR(CONVERT(A2,"km","mi"), "Invalid units") returns the fallback text instead of propagating #N/A into downstream formulas.2

The most common unit code mistakes

Excel does not recognise 'lb' (use 'lbm'), 'celsius' (use 'C'), 'fahrenheit' (use 'F'), 'meter' (use 'm'), or 'kilometer' (use 'km'). The unit codes are case-sensitive in some Excel versions, which catches users who expect case insensitivity. 'C' converts Celsius correctly, while 'c' may return #N/A in those same versions. When a CONVERT() call returns #N/A unexpectedly, isolate the formula in an empty cell, replace cell references with literal values, and test each unit code individually until you identify the failing argument. This systematic approach saves time compared to guessing which part of the formula caused the error.

A quick defensive habit is to keep a small reference table of the correct codes on a hidden worksheet, so anyone editing the workbook can check lbm against lb before typing. That table also doubles as the source for a data validation list, which is the more robust fix described further below, removing the most common source of unexpected #N/A errors before they can propagate into a downstream calculation.

Pressure, energy, power, speed, and data unit codes

Across its full range, Excel's CONVERT() covers measurement categories most engineers encounter beyond length, mass, and temperature. For pressure, valid codes include 'Pa' (pascal), 'psi', 'atm' (atmosphere), and 'mmHg' (millimetres of mercury). Energy accepts 'J' (joule), 'cal' (thermochemical calorie), 'kcal', 'Wh' (watt-hour), 'BTU', and 'eV' (electronvolt). Power accepts 'W' (watt) and 'HP' (horsepower). Speed accepts 'm/s' and 'mph'.1

For data storage, CONVERT() recognises 'bit', 'byte', 'kB', 'MB', 'GB', and 'TB', which is useful for capacity tables and storage reporting worksheets. Time conversions use 'sec', 'mn', 'hr', 'day', and 'yr'. Notably, CONVERT() does not support fuel efficiency units; for L/100km to mpg-US conversion, use the formula =235.21/A1 where A1 holds the L/100km value.3 These arithmetic workarounds are necessary for any unit pair not present in Excel's built-in list.

Excel's CONVERT() also accepts SI metric prefix strings prepended to supported base unit codes, which extends the effective range beyond what Microsoft's documentation lists. Prefixes expand your options significantly. By combining 'k' (kilo), 'M' (mega), 'G' (giga), 'm' (milli), 'u' (micro), and 'n' (nano) with SI-derived base codes for mass, length, and energy, you can express values at any scale; =CONVERT(1, "Mm", "km") converts one megametre to 1000 kilometres, and =CONVERT(500, "nJ", "J") converts 500 nanojoules to joules without intermediate arithmetic. The prefix system applies only to SI-derived base codes; it does not extend to imperial codes like 'lbm', 'ft', or 'BTU'. Use prefixed forms to avoid intermediate calculations when your data contains nanometre-scale measurements or gigajoule-scale energy values.

Array formulas and applying CONVERT() across large datasets

Array formulas extend CONVERT() from single-cell operations to entire column ranges without copying the formula to each row. Dynamic arrays make this effortless. In Microsoft 365 and Excel 2019 with dynamic arrays, entering =CONVERT(A2:A100, "kg", "lbm") in a single cell spills the converted values across 99 rows automatically.4 In older Excel versions, press Ctrl+Shift+Enter instead of Enter to create a legacy array formula; Excel wraps it in curly braces to indicate the array context.

Using CONVERT() inside pivot table source data

For pivot tables that display values in a different unit from the source data, apply CONVERT() in a helper column before adding the data to the pivot table. Add a column with the header 'Mass (lbm)' and fill it with =CONVERT(B2,"kg","lbm"). This keeps the source data in its original units while making the converted column available as a pivot field. Avoid attempting to apply CONVERT() inside the pivot's value field settings; that path is unavailable for this function, and a calculated field workaround is the only alternative.

Combining CONVERT() with data validation for unit selection

Pairing CONVERT() with Excel data validation dropdowns creates a self-service unit conversion sheet where users pick source and target units from lists rather than typing codes manually. Set up a named range of valid unit codes, apply data validation to the from-unit and to-unit cells, and reference those cells inside the CONVERT() formula. This approach eliminates the most common #N/A errors caused by misspelled or invalid unit codes, and it makes the spreadsheet accessible to users who do not memorize the full code list.5

Notes

Syntax: CONVERT(number, from_unit, to_unit). Unit codes are short strings: "m" (metre), "mi" (mile), "kg" (kilogram), "lbm" (pound-mass, not "lb"), "C" (Celsius), "F" (Fahrenheit). Returns #N/A for incompatible units or unrecognised codes. Also works in Google Sheets.

Examples

Length

=CONVERT(5, "km", "mi")
// 3.10685596

Temperature

=CONVERT(100, "C", "F")
// 212

Mass

=CONVERT(70, "kg", "lbm")
// 154.323584

Use "lbm" for pound-mass. "lb" is not a valid code.

Verify with the Engineering Unit Converter tool.

Length

=CONVERT(5, "km", "mi")
// 3.10685596

Code says: 3.10685596

Temperature

=CONVERT(100, "C", "F")
// 212

Code says: 212

Mass

=CONVERT(70, "kg", "lbm")
// 154.323584

Use "lbm" for pound-mass. "lb" is not a valid code.

Code says: 154.323584

CONVERT() reference

  • =235.21/A1
  • =CONVERT(70,"kg","lbm") → 154.323584
  • 'lb' is invalid — use 'lbm' for pound-mass

CONVERT() returns #N/A for incompatible dimensions or unrecognized unit codes.

Sources
  1. 1.

    Microsoft, "CONVERT function," support.microsoft.com, accessed June 2026. https://support.microsoft.com/en-us/excel/functions/convert-function

  2. 2.

    Alan Murray, "How to Hide Error Values and Indicators in Microsoft Excel," howtogeek.com, November 2019. https://www.howtogeek.com/442863/how-to-hide-error-values-and-indicators-in-microsoft-excel/

  3. 3.

    NIST, "NIST Guide to the SI, Appendix B.8: Factors for Units Listed Alphabetically," SP 811, nist.gov, accessed June 2026. https://www.nist.gov/pml/special-publication-811/nist-guide-si-appendix-b-conversion-factors/nist-guide-si-appendix-b8

  4. 4.

    Microsoft, "Dynamic array formulas and spilled array behavior," support.microsoft.com, accessed June 2026. https://support.microsoft.com/en-us/excel/dynamic-array-formulas-and-spilled-array-behavior

  5. 5.

    Tony Phillips, "Everything you need to know about drop-down lists in Microsoft Excel," howtogeek.com, June 2026. https://www.howtogeek.com/microsoft-excel-data-validation-drop-down-lists/

FAQ

Unit Conversion in Rust with the uom Crate

Uom (Units of Measurement) is a Rust crate that enforces dimensional correctness at compile time using the type system.1 Unit mismatches produce compile errors, not runtime panics. It covers length, mass, temperature, pressure, and many other physical quantities out of the box.2

Adding uom to Cargo.toml and creating typed quantity instances

Adding uom to a Rust project requires a single entry in Cargo.toml with the correct feature flags. The most common setup is uom = { version = "0.36", features = ["f64", "si"] }, which activates the full SI quantity system for 64-bit floats. If your project needs both f32 and f64 quantities, list both: features = ["f32", "f64", "si"].3 The si feature unlocks the SI module, providing pre-defined types for every SI quantity including Length, Mass, ThermodynamicTemperature, and Velocity, and this compile-time type safety is what makes uom fundamentally different from runtime unit libraries that only catch mismatches when the code actually runs.

Creating quantities with new::() and reading values with get::()

You create a quantity with the ::new::<unit>(value) constructor, which stores the value internally in SI base units regardless of which unit you specified at creation time, so unit selection is purely an input and output concern that never affects the precision of intermediate calculations. Length::new::<kilometre>(5.0) stores 5 kilometres internally as SI metres. ThermodynamicTemperature::new::<degree_celsius>(100.0) stores 100°C internally as kelvin. To read the value in any unit, call .get::<unit>(), which returns a raw f64 with the conversion applied. All internal arithmetic operates on SI base units, so unit selection is purely an input and output concern that never affects the precision of intermediate calculations.

When the compiler rejects mixed-unit arithmetic

When you assign a mass value to a length variable or add two quantities of different dimensions, the Rust compiler produces a type mismatch error before the program builds, and this feedback arrives during development rather than in production so unit confusion bugs surface before any incorrect values propagate to sensors, dashboards, or downstream services that depend on physically meaningful results. let d: Length<SI<f64>, f64> = mass_value; is a compile-time error, and the expected and found types appear in the compiler output from cargo build.4

Dimensional algebra and scale normalization

This feedback arrives during development, not in production, so unit confusion bugs surface before any incorrect values propagate to sensors, dashboards, or downstream services. The type system also handles scale differences correctly, since passing a value stored in metres where a function accepts kilometres is not a type error in uom: both are Length<SI<f64>, f64>, and the internal SI representation normalizes both to metres regardless of which unit was used at creation. Furthermore, uom enforces dimensional algebra for derived quantities: multiplying Length by Length produces Area, and dividing Length by Time produces Velocity, all tracked by the type system automatically.

In no_std environments and performance-critical code

In embedded systems projects where the standard library is unavailable, uom supports no_std operation by disabling the default std feature: uom = { version = "0.36", default-features = false, features = ["f64", "si"] }. Without std, the crate still performs full dimensional analysis and unit conversion; it cannot use heap allocation or platform I/O. This makes uom a viable choice for microcontroller firmware where sensor readings need unit conversion without the overhead of a full OS environment.

Compile-time performance and zero-cost conversion

The performance argument for uom is straightforward: the Rust compiler optimizes quantity arithmetic to the same machine instructions as equivalent raw-float code. Calling .get::<unit>() resolves to a multiplication by a compile-time constant with no runtime lookup table or dispatch overhead.1 Build with cargo build in release mode and inspect the output with cargo asm if you need to verify the generated machine code for a specific quantity type in a performance-critical path.

For domain-specific measurement needs that extend beyond SI, uom provides two extension paths. Adding a unit to an existing quantity uses the unit! macro: specify the SI quantity module, a conversion ratio to the base unit, and a display string. The conversion ratio must be exact. Pointing unit! at uom::si::length and providing the metre-equivalent ratio integrates a custom length unit into the type system without any hand-rolled conversion code. For an entirely new physical dimension with no SI equivalent, the quantity! macro combined with a system! block generates typed structs, constructors, and Display implementations automatically. For most embedded and scientific projects, the built-in SI system already covers Pressure, ElectricCurrent, ElectricPotential, and Frequency without any extension.5

Notes

Add to Cargo.toml: uom = { version = "0.36", features = ["f64", "si"] }. Quantities are typed generics like Length, f64>. Conversion uses .get::() which returns a raw f64. The Rust compiler catches mixed-unit arithmetic as a type error before the program runs.

Examples

Basic conversion

use uom::si::f64::*;
use uom::si::length::{kilometre, mile};

let d = Length::new::<kilometre>(5.0);
println!("{} mi", d.get::<mile>());
// 3.1068559611866697 mi

Temperature

use uom::si::thermodynamic_temperature::{degree_celsius, degree_fahrenheit};

let t = ThermodynamicTemperature::new::<degree_celsius>(100.0);
println!("{} °F", t.get::<degree_fahrenheit>());
// 212 °F

Verify with the Engineering Unit Converter tool.

Basic conversion

use uom::si::f64::*;
use uom::si::length::{kilometre, mile};

let d = Length::new::<kilometre>(5.0);
println!("{} mi", d.get::<mile>());
// 3.1068559611866697 mi

Code says: 3.1068559611866697 mi

Temperature

use uom::si::thermodynamic_temperature::{degree_celsius, degree_fahrenheit};

let t = ThermodynamicTemperature::new::<degree_celsius>(100.0);
println!("{} °F", t.get::<degree_fahrenheit>());
// 212 °F

Code says: 212 °F

uom crate reference

  • 3.1068559611866697 mi
  • 212 °F
  • uom = { version = "0.36", features = ["f64", "si"] }

Mixing Length and Mass in an arithmetic expression is a compile-time type error, not a runtime panic.

Sources
  1. 1.

    Mike Boutin, "uom," docs.rs, accessed June 2026. https://docs.rs/uom/0.36.0/uom/index.html

  2. 2.

    Mike Boutin, "uom::si," docs.rs, accessed June 2026. https://docs.rs/uom/0.36.0/uom/si/index.html

  3. 3.

    Mike Boutin, "uom 0.36.0 Cargo.toml," github.com, March 2024. https://github.com/iliekturtles/uom/blob/v0.36.0/Cargo.toml

  4. 4.

    Mike Boutin, "uom: Units of Measurement," github.com, accessed June 2026. https://github.com/iliekturtles/uom

  5. 5.

    JCGM, "[VIM3] 1.16 International System of Units," jcgm.bipm.org, accessed June 2026. https://jcgm.bipm.org/vim/en/1.16.html

FAQ

Additional resources

Engineering Unit Converter: Code ExamplesPython (Pint), JavaScript (convert-units), Excel CONVERT(), and Rust (uom) snippets that reproduce the same length, mass, and pressure conversions the tool runs live.Engineering Unit Converter: ConversionsLength, mass, temperature, pressure, energy, power, speed, and five other dimensions converted with worked examples, the largest conversion set on the site.