UnitFormat.js is a number formatter for human readable unit numbers, like 10km, 5GB, 17kHz, 220MW, ... with known metric suffixes.
You can install UnitFormat.js via npm:
npm install unitformatOr with yarn:
yarn add unitformatAlternatively, download or clone the repository:
git clone https://github.com/rawify/UnitFormat.jsInclude the unitformat.min.js file in your project:
<script src="path/to/unitformat.min.js"></script>
<script>
var x = UnitFormat(10000);
</script>Or in a Node.js project:
const unitFormat = require('unitformat');or
import unitFormat from 'unitformat';The interface of UnitFormat.js is a single function that basically takes the number to be formatted and optionally the base unit, like "m" for meters:
let a = UnitFormat(1000, "m") // 1km
let b = UnitFormat(20000, "Hz") // 20kHz
let c = UnitFormat(1000) // 1k
let d = UnitFormat(0.02, "m") // 2cmThe whole package consists of a single function UnitFormat with the following signature
UnitFormat(num, baseUnit="", prefixes="kMGTPE", base=10)- num: the number to be formatted
- baseUnit: the base unit, like meters, Hertz, Joule, ...
- suffix: which suffixes should be used
- base: The number base, default is 10, but 2 is also possible for bytes
The suffix parameter is a string list of single-character metric prefixes, like kMGTPE. For base 10 the following prefixes can be used:
E: ExaP: PetaT: TeraG: GigaM: Megak: Kiloh: Hectod: Decic: Centim: Milliu: Micron: Nanop: Picof: Femtoa: Atto
And for base 2 the following prefixes are possible:
k: KiloM: MegaG: GigaT: TeraP: PetaE: Exa
Like all my libraries, UnitFormat.js is written to minimize size after compression with Google Closure Compiler in advanced mode. The code style is optimized to maximize compressibility. If you extend the library, please preserve this style.
After cloning the Git repository run:
npm install
npm run build
Testing the source against the shipped test suite is as easy as
npm run test
Copyright (c) 2025, Robert Eisele Licensed under the MIT license.