javascript
28 lines · 8 steps
Formatting byte counts into human units
A function that scales a raw byte count into the right unit with a logarithm and formats it cleanly.
Explained by
highlit
1const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB'];
2
3export function formatBytes(bytes, { decimals = 1, binary = false } = {}) {
4 if (!Number.isFinite(bytes)) {
5 throw new TypeError('bytes must be a finite number');
6 }
7
8 const sign = bytes < 0 ? '-' : '';
9 let value = Math.abs(bytes);
10
11 if (value < 1) {
12 return `${sign}${value} B`;
13 }
14
15 const base = binary ? 1024 : 1000;
16 const exponent = Math.min(
17 Math.floor(Math.log(value) / Math.log(base)),
18 UNITS.length - 1
19 );
20
21 value /= base ** exponent;
22
23 const rounded = value.toFixed(exponent === 0 ? 0 : decimals);
24 const unit = UNITS[exponent];
25 const suffix = binary && exponent > 0 ? unit.replace('B', 'iB') : unit;
26
27 return `${sign}${parseFloat(rounded)} ${suffix}`;
28}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A base-N logarithm tells you which unit a value falls into without a loop or lookup chain.
- 2Clamping the exponent to the units array length guards against overflowing past the largest known unit.
- 3Splitting off the sign early lets the rest of the math work on a clean positive magnitude.
Related explainers
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
javascript
const SWIPE_THRESHOLD = 80; const MAX_TRANSLATE = 120; export function attachSwipeToDismiss(element, onDismiss) {
Building a swipe-to-dismiss gesture in JS
touch-events
gesture-detection
dom-manipulation
Intermediate
10 steps
javascript
const { pool } = require('./db'); function withTransaction() { return async (req, res, next) => {
A per-request transaction middleware in Express
middleware
database-transactions
connection-pooling
Advanced
7 steps
javascript
function collapseConsecutiveLogs(lines, { keyFn = (l) => l.message } = {}) { const groups = []; for (const line of lines) {
Collapsing consecutive log lines in JavaScript
grouping
run-length-encoding
data-transformation
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/formatting-byte-counts-into-human-units-explained-javascript-e5f0/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.