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
- 5 km → mile 3.1068559611866697 mi
- 100°C → °F (via Quantity()) 212.0 °F
- Custom unit example 1 furlong = 201.168 m
Use ureg.Quantity(value, ureg.degC) for absolute temperatures — the multiplication form (value * ureg.degC) skips the offset.
- 1.
"Tutorial," Pint, pint.readthedocs.io, accessed June 2026. https://pint.readthedocs.io/en/stable/getting/tutorial.html
- 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.
"Furlong," Wikipedia, accessed June 2026. https://en.wikipedia.org/wiki/Furlong
- 4.
"Dimensional analysis," Wikipedia, accessed June 2026. https://en.wikipedia.org/wiki/Dimensional_analysis
- 5.
"Universal functions (ufunc)," NumPy, numpy.org, accessed June 2026. https://numpy.org/doc/stable/reference/ufuncs.html
Yes. pint Quantities wrap NumPy arrays transparently. All standard ufuncs preserve units and broadcasting works as expected.
Use ureg.Quantity(value, ureg.degC) rather than value * ureg.degC for absolute temperatures. The multiplication form treats the temperature as a difference and skips the 32-degree offset.
Yes. ureg.define("furlong = 201.168 m") registers a new unit that works in all conversion and arithmetic contexts.
pint raises pint.DimensionalityError immediately. Adding metres to kilograms throws rather than silently producing a wrong number.
Yes, though it adds runtime overhead compared to raw floats. For performance-critical loops, convert to base units first and wrap at the I/O boundary. CapyToolkit takes a similar approach on the client side, running every unit conversion in your browser so the raw numbers never leave your device.
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
- 5 km → mile 3.1068559611866697
- 100°C → °F 212
- Bundle size ~20 kB minified
convert-units throws immediately on an unrecognized unit string rather than returning undefined.
- 1.
"convert-units," GitHub, github.com, accessed June 2026. https://github.com/convert-units/convert-units
- 2.
"convert-units," npm, npmjs.com, accessed June 2026. https://npmjs.com/package/convert-units
- 3.
"convert-units," GitHub, github.com, accessed June 2026. https://raw.githubusercontent.com/convert-units/convert-units/main/README.md
- 4.
"Npm (software)," Wikipedia, accessed June 2026. https://en.wikipedia.org/wiki/Npm_(software)
- 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
Yes. The package ships with official TypeScript definitions. The .from() and .to() arguments are typed as union literals so invalid unit strings are caught at compile time.
The base package does not support custom units. For extensibility, build a thin wrapper around the conversion factors, or switch to a library like js-quantities that accepts custom definitions.
convert-units handles the Celsius-to-Fahrenheit offset correctly using a formula rather than a simple multiplier.
Yes. convert-units has zero dependencies and tree-shakes cleanly with modern bundlers. The full package is under 20 kB minified.
Call convert().measures() to list all measurement categories, or convert().possibilities() for every unit across all categories. CapyToolkit uses a similar discovery approach for its own browser-based conversion engine, pre-loading the full unit table so every conversion runs locally.
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
- L/100km → mpg-US =235.21/A1
- 70 kg → lbm =CONVERT(70,"kg","lbm") → 154.323584
- Common mistake 'lb' is invalid — use 'lbm' for pound-mass
CONVERT() returns #N/A for incompatible dimensions or unrecognized unit codes.
- 1.
Microsoft, "CONVERT function," support.microsoft.com, accessed June 2026. https://support.microsoft.com/en-us/excel/functions/convert-function
- 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.
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.
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.
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/
CONVERT() has been available since Excel 2003. It works in all modern versions including Excel for Mac and Excel Online (Microsoft 365).
"lbm" is pound-mass. Excel does not recognise "lb" as a valid unit code, and using it returns #N/A.
No. There is no built-in L/100km or mpg unit. Use a formula instead: for L/100km to mpg-US, use =235.21/A1 where A1 contains the L/100km value.
CONVERT() returns #N/A. For example, =CONVERT(5, "km", "kg") always errors because length and mass are dimensionally incompatible.
Yes. Google Sheets supports CONVERT() with the same syntax and most of the same unit codes as Excel. For unit pairs that neither Excel nor Google Sheets cover, CapyToolkit fills the gap with a browser-based converter that handles fuel efficiency, torque, and other less common dimensions.
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
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
- 5 km → mile 3.1068559611866697 mi
- 100°C → °F 212 °F
- Cargo feature flags 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.
- 1.
Mike Boutin, "uom," docs.rs, accessed June 2026. https://docs.rs/uom/0.36.0/uom/index.html
- 2.
Mike Boutin, "uom::si," docs.rs, accessed June 2026. https://docs.rs/uom/0.36.0/uom/si/index.html
- 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.
Mike Boutin, "uom: Units of Measurement," github.com, accessed June 2026. https://github.com/iliekturtles/uom
- 5.
JCGM, "[VIM3] 1.16 International System of Units," jcgm.bipm.org, accessed June 2026. https://jcgm.bipm.org/vim/en/1.16.html
Yes. Assigning a mass value to a length variable is a type error caught by the Rust compiler before the program runs.
The most common setup is features = ["f64", "si"]. Add "f32" if you need single precision. The "si" feature activates the SI quantity types.
uom stores all quantities in SI internally. .new::<mile>(5.0) stores as metres; .get::<kilometre>() retrieves in kilometres. You never manually multiply by a conversion factor.
Yes. uom provides a quantity! macro for extending the system with user-defined dimensions and unit types.
Yes. Disable the default std feature and add no-std compatible backends. The core quantity arithmetic does not require the standard library. CapyToolkit applies the same zero-server principle to its own unit conversions, running every calculation in your browser without transmitting the values.