Unit Conversion in JavaScript
Convert measurement units in JavaScript — length, temperature, weight, and data sizes with browser APIs.
Published:
Tags: unit conversion JavaScript, JavaScript unit converter, convert units JS
Unit Conversion in JavaScript JavaScript handles unit conversion through simple arithmetic functions. The language has no built-in unit type, but the API can format numbers with unit labels, and the 'unit' style handles display formatting for many common units. --- Common Unit Conversions | From | To | Factor | |------|-----|--------| | km | miles | ÷ 1.60934 | | kg | pounds | × 2.20462 | | °C | °F | × 9/5 + 32 | | m | feet | × 3.28084 | | liters | gallons (US) | ÷ 3.78541 | | cm | inches | ÷ 2.54 | Basic Conversion Functions Store conversion factors as named constants, then write thin wrapper functions: Temperature Conversion Temperature requires dedicated functions because it involves offset, not just scaling: Data Size Conversions Using Intl.NumberFormat for Unit Display The 'unit'…
Frequently Asked Questions
How do I convert units in JavaScript?
Multiply by a conversion factor. Example: function kmToMiles(km) { return km * 0.621371; }. For temperature, use offset functions: function celsiusToFahrenheit(c) { return c * 9/5 + 32; }. Store conversion factors as named constants for maintainability.
What JavaScript libraries handle unit conversion?
js-quantities (small, browser-friendly), convert-units (npm, broad coverage), mathjs (full CAS with unit support), and convert (TypeScript-first). For most cases, plain conversion factors in a constants file are sufficient and add zero bundle size.
How do I convert Celsius to Fahrenheit in JS?
const celsiusToFahrenheit = (c) => c * 9/5 + 32; — this is a pure function. Inverse: const fahrenheitToCelsius = (f) => (f - 32) * 5/9. Both can be used directly in React state or in a utility module.
How do I format units in JavaScript Intl?
The Intl.NumberFormat 'unit' style: new Intl.NumberFormat('en-US', {style: 'unit', unit: 'meter'}).format(100) returns '100 m'. Supported units include 'kilometer', 'mile', 'fahrenheit', 'celsius', 'kilogram', 'pound', 'liter'. See MDN for the full list.
How do I convert bytes to MB in JavaScript?
const bytesToMB = (bytes) => bytes / 1_000_000; for decimal MB. For mebibytes (binary): const bytesToMiB = (bytes) => bytes / (1024 * 1024). Display with formatting: (1_234_567 / 1_000_000).toFixed(2) + ' MB'.
All articles · theproductguy.in