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
const express = require('express'); const router = express.Router(); const { pool } = require('../db'); const redis = require('../redis');
Building a health check endpoint in Express
health-check
timeouts
promise-race
Intermediate
9 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
javascript
const MAX_BATCH_SIZE = 20; const FLUSH_INTERVAL = 5000; const ENDPOINT = '/api/analytics';
Batching analytics events in the browser
batching
buffering
sendbeacon
Intermediate
10 steps
javascript
export function diffIds(current, desired) { const currentSet = new Set(current); const desiredSet = new Set(desired);
Diffing sets to sync group membership
set-operations
diffing
transactions
Intermediate
8 steps
javascript
class HistoryStack { constructor(initial = '', limit = 100) { this.past = []; this.present = initial;
Building an undo/redo history stack
undo-redo
state-management
debouncing
Intermediate
7 steps
javascript
import { useState, useCallback, useRef } from 'react'; function LikeButton({ postId, initialLiked, initialCount }) { const [liked, setLiked] = useState(initialLiked);
Optimistic like button with React
optimistic-ui
abortcontroller
error-handling
Advanced
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.