UnitFormat.js Examples

Download Back To CSSScript.Com

A tiny JavaScript library for formatting numbers into human-readable metric units.

UnitFormat.js Demo

Result:

12.345km

Usage & Examples

Browser

<script src="unitformat.min.js"></script>
<script>
  const formatted = UnitFormat(1000, "m"); // "1km"
</script>

Node.js (ESM)

import UnitFormat from 'unitformat';

const formatted = UnitFormat(20000, "Hz"); // "20kHz"

More Examples

UnitFormat(1000)"1k"

UnitFormat(0.02, "m")"2cm"

UnitFormat(1048576, "B", "kMGTPE", 2)"1MB"

UnitFormat(12345, "W", "kM")"12.345kW"

UnitFormat(-5000000, "J")"-5MJ"

Parameters

UnitFormat(num, baseUnit, suffixes, base)
Parameter Type Default Description
num Number - The number to be formatted.
baseUnit String "" The base unit (e.g., "m", "Hz", "B").
suffixes String "kMGTPE" A string of single-character metric prefixes to use.
base Number 10 The number base, 10 for decimal or 2 for binary.

Available Suffixes

Base 10 (Decimal)

E, P, T, G, M, k, h, d, c, m, u, n, p, f, a

Base 2 (Binary)

E, P, T, G, M, k