惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 叶小钗
Microsoft Azure Blog
Microsoft Azure Blog
Stack Overflow Blog
Stack Overflow Blog
Jina AI
Jina AI
Vercel News
Vercel News
H
Help Net Security
Martin Fowler
Martin Fowler
美团技术团队
云风的 BLOG
云风的 BLOG
Y
Y Combinator Blog
阮一峰的网络日志
阮一峰的网络日志
MyScale Blog
MyScale Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
博客园 - 三生石上(FineUI控件)
博客园 - 司徒正美
人人都是产品经理
人人都是产品经理
Engineering at Meta
Engineering at Meta
G
Google Developers Blog
Blog — PlanetScale
Blog — PlanetScale
MongoDB | Blog
MongoDB | Blog
宝玉的分享
宝玉的分享
小众软件
小众软件
T
Tailwind CSS Blog
WordPress大学
WordPress大学

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
I Built a Unit Converter in Pure Vanilla JS — 7 Categorie...
Dev Nestio · 2026-06-28 · via DEV Community

Dev Nestio

Unit converters are everywhere online, but they all seem to either require an account, run ads that cover half the screen, or send your input to a server for no reason. I built one that runs entirely in your browser, with no dependencies, no tracking, and no round-trips.

👉 https://unit-converter-dev.pages.dev

What It Does

Seven conversion categories, 70+ units, real-time bidirectional conversion:

Category Example units
Length mm, cm, m, km, in, ft, yd, mi, nmi, light-year
Weight mg, g, kg, t, oz, lb, st, short ton
Temperature °C, °F, K, °R
Volume ml, l, m³, fl oz, cup, pint, quart, gallon, tbsp, tsp
Area mm², cm², m², km², ha, acre, ft², in², mi², yd²
Speed m/s, km/h, mph, ft/s, knot, Mach
Data bit, byte, KB/KiB, MB/MiB, GB/GiB, TB — both SI and binary

Features:

  • Bidirectional — type in either field, the other updates instantly
  • Swap button — flip from/to with one click
  • All-units panel — see your input converted to every unit in the category simultaneously
  • Formula display — shows the conversion factor (e.g. "1 Mile = 1.609344 Kilometer")
  • Zero dependencies — single HTML file, no build step, no npm

Implementation Notes

Linear vs. non-linear conversions

Most unit conversions are linear: multiply by a factor to get to the base unit, divide by another factor to get to the target. The approach:

function convert(catKey, fromUnit, toUnit, value) {
  const base = toBase(catKey, fromUnit, value);     // → base unit
  return fromBase(catKey, toUnit, base);            // base unit → target
}

function toBase(catKey, unit, value) {
  const u = CATEGORIES[catKey].units[unit];
  if (u.toBase) return u.toBase(value);             // non-linear (temperature)
  return value * u.factor;
}

Temperature is the classic non-linear case. You can't just multiply to convert between Celsius, Fahrenheit, and Kelvin — you need offset arithmetic:

temperature: {
  units: {
    C: {
      toBase:   v => v + 273.15,               // °C → K
      fromBase: v => v - 273.15,               // K → °C
    },
    F: {
      toBase:   v => (v - 32) * 5/9 + 273.15, // °F → K
      fromBase: v => (v - 273.15) * 9/5 + 32, // K → °F
    },
    K: { toBase: v => v, fromBase: v => v },
    R: { toBase: v => v * 5/9, fromBase: v => v * 9/5 },
  }
}

SI vs. binary data units

The data category includes both SI prefixes (1 KB = 1000 bytes) and binary prefixes (1 KiB = 1024 bytes). Both are represented with the same factor-based approach, just stored as separate units:

data: {
  units: {
    kB:  { factor: 8e3     },  // Kilobyte  = 8000 bits
    kiB: { factor: 8192    },  // Kibibyte  = 8192 bits (= 8 × 1024)
    mB:  { factor: 8e6     },  // Megabyte  = 8,000,000 bits
    miB: { factor: 8388608 },  // Mebibyte  = 8,388,608 bits (= 8 × 1024²)
    // ...
  }
}

Number formatting

The tricky part is displaying results cleanly. 1.6093440000000001 is ugly; 1.609344 is what you want. toPrecision(10) then parseFloat removes trailing zeros while keeping enough precision:

function formatNum(n) {
  if (!isFinite(n)) return '';
  if (n === 0) return '0';
  const abs = Math.abs(n);
  if (abs >= 1e-3 && abs < 1e13) {
    return parseFloat(n.toPrecision(10)).toString();
  }
  return n.toExponential(6);  // very large or very small → scientific notation
}

Testing

165 tests, all passing, using only Node.js assert:

§1  Length conversions         (17 tests)
§2  Weight conversions         (12 tests)
§3  Temperature conversions    (13 tests)
§4  Volume conversions         (11 tests)
§5  Area conversions           (10 tests)
§6  Speed conversions          ( 9 tests)
§7  Data conversions           (12 tests)
§8  formatNum                  (15 tests)
§9  convert edge cases         ( 8 tests)
§10 Roundtrip conversions      (13 tests)
§11 Category structure         (12 tests)
§12 Known reference values     (13 tests)
§13 Additional coverage        (20 tests)

Highlights from the test suite:

  • -40°C = -40°F (the only point where Celsius and Fahrenheit are equal)
  • 0 K = -459.67°F (absolute zero)
  • 1 mi = 5280 ft = 1760 yd = 1.609344 km
  • 1 GiB = 1024 MiB = 8589934592 bits
  • Roundtrip tests: convert A→B→A and verify you get A back (within floating-point tolerance)

Try It

👉 https://unit-converter-dev.pages.dev

Part of devnestio — a collection of free, zero-dependency developer tools that run entirely in your browser.