JavaScript Unit Converter: Build One With Exact Factors

Build a JavaScript unit converter with exact official factors: a base unit table, length and weight math, temperature formulas, clean rounding and a live demo.

Share this post
7 min read

Last updated December 3, 2026

A JavaScript unit converter turns a value from one unit into another, such as inches to centimeters. The cleanest way is to store one factor per unit, relative to a base unit.

Many tutorials write a new function for every pair of units and use rounded numbers. This guide uses exact official factors, one simple formula, and a live demo you can try first.

Key Takeaways

  • Pick a base unit for each type, such as meters for length.
  • Store one factor per unit, then convert with value times from divided by to.
  • Use exact factors: 1 inch is exactly 2.54 centimeters, per the National Institute of Standards and Technology (NIST).
  • Temperature needs formulas, because 0 degrees is not the same point on every scale.
  • Round results with toPrecision to hide tiny floating point errors.

Live demo: Digieh unit converter

Digieh tool. Factors are the exact definitions from the US National Institute of Standards and Technology (NIST). Results are rounded to 10 significant digits.

Exact, not rounded. The demo uses the official definitions, such as 0.3048 meters per foot. Rounded factors like 0.3937 for inches add small errors that grow with large values.

Why Use a Base Unit Table?

With 8 length units, there are 56 possible pairs. Writing a function for each pair is slow and easy to get wrong.

A base unit table needs only 8 numbers. Every conversion goes through the base unit, so adding a new unit means adding one line.

ApproachNumbers to store for 8 unitsAdding a 9th unit
One function per pair56 conversions16 new conversions
Base unit table8 factors1 new factor

Source: Digieh calculation, based on units in the standards institute guide. Pairs are 8 times 7.

Step 1: How Do You Set Up the Page?

You need a number box, two drop-down lists and a place for the result.

<input id="value" type="number" value="1">
<select id="from"></select>
<select id="to"></select>
<p id="result"></p>

Fill the drop-down lists from your unit table with JavaScript. That way the lists always match the units you support.

Step 2: Which Conversion Factors Are Exact?

Since 1959, the inch, foot, yard, mile and pound have exact metric definitions. You can use them with no rounding.

UnitExact valueOfficial source
1 inch0.0254 meters, or 25.4 millimetersStandards institute length page
1 foot0.3048 metersStandards institute conversion guide
1 yard0.9144 metersStandards institute length page
1 mile1,609.344 metersStandards institute conversion guide
1 pound0.45359237 kilogramsHandbook 44 history

Sources: length units page, conversion guide and Handbook 44 from the standards institute, read December 3, 2026.

The institute explains that a 1958 agreement among English-speaking nations set these values. They took effect in the United States on July 1, 1959.

Some units have no exact factor in that table. The US liquid gallon is listed as about 3.785412 liters.

2.54Digieh checked the standards institute length page on December 3, 2026. One inch is exactly 2.54 centimeters, so no rounding is needed for inches.

Step 3: How Do You Write the Converter?

// One factor per unit: how many base units (meters, kilograms) it equals
var UNITS = {
  length: { m: 1, km: 1000, cm: 0.01, mm: 0.001,
            in: 0.0254, ft: 0.3048, yd: 0.9144, mi: 1609.344 },
  mass:   { kg: 1, g: 0.001, lb: 0.45359237, oz: 0.45359237 / 16 }
};

function convert(type, value, from, to) {
  return value * UNITS[type][from] / UNITS[type][to];
}

convert('length', 1, 'in', 'cm');   // 2.54
convert('mass', 1, 'kg', 'lb');     // 2.2046226218487757

The formula multiplies by the from factor to reach the base unit. Then it divides by the to factor.

The ounce is defined as one sixteenth of a pound, so the code divides the pound factor by 16. That keeps it exact.

Try this today. In the demo, convert 1 mile to kilometers. You should see exactly 1.609344, which matches the official definition.

Free updates

Join the Digieh list

Be the first to know when our weekly brief launches.

No spam. Unsubscribe anytime. Read our Privacy Policy.

Step 4: How Do You Convert Temperature?

Temperature scales do not start at the same zero, so a single factor will not work. Convert to Celsius first, then to the target unit.

function convertTemp(value, from, to) {
  // Step 1: turn any input into Celsius
  var c = from === 'C' ? value
        : from === 'F' ? (value - 32) / 1.8
        : value - 273.15;              // from kelvin
  // Step 2: turn Celsius into the target unit
  return to === 'C' ? c
       : to === 'F' ? c * 1.8 + 32
       : c + 273.15;                   // to kelvin
}

The standards institute guide gives the Fahrenheit to Celsius formula as the Fahrenheit value minus 32, divided by 1.8. Both numbers are exact.

Source: Special Publication 811, Appendix B8, read December 3, 2026.

InputResultCheck
100 Celsius212 FahrenheitWater boils at sea level
0 Celsius273.15 kelvinExact offset
minus 40 Celsiusminus 40 FahrenheitThe two scales meet here

Source: Digieh test of the convertTemp function in Node.js 22, December 3, 2026.

Step 5: How Do You Hide Tiny Rounding Errors?

Floating point math can leave tiny errors. In Digieh’s test, 98.6 Fahrenheit came out as 36.99999999999999 Celsius.

function tidy(n) {
  return Number(n.toPrecision(10));   // 36.99999999999999 becomes 37
}

toPrecision keeps a set number of significant digits. Ten digits is more than enough for everyday conversions, and it turns the result into a clean 37.

See the MDN toPrecision reference for details.

How Do You Show More Than One Result at Once?

Some users want to see a value in every unit at the same time. Loop over the table and convert to each unit.

function convertAll(type, value, from) {
  var out = {};
  Object.keys(UNITS[type]).forEach(function (to) {
    out[to] = tidy(convert(type, value, from, to));
  });
  return out;
}

This is handy for a reference card, such as one meter shown in feet, inches, yards and miles together.

Show the results in a small table, and keep the unit names next to the numbers so nothing is unclear.

How Do You Make the Converter Easy to Use?

  • Update the result as the user types, using the input event.
  • Add a swap button that flips the from and to units.
  • Remember the last units in the browser, so users do not pick them again.
  • Use full unit names in the lists, not only short symbols.
  • Show a short note when a unit has a country version, such as gallons.

Our demo updates live and uses full names, which helps people who are not sure of the symbols.

What Other Units Can You Add?

  • Area, using square meters as the base unit.
  • Volume, using liters as the base unit.
  • Speed, using meters per second as the base unit.
  • Digital storage, using bytes, with 1,000 or 1,024 steps clearly labeled.
  • Cooking units, with a note that cups differ by country.

Keep each type in its own table. Never mix length and weight in one table, or users could convert meters into pounds.

Need sizes instead of units? Our US to UK shoe size converter uses official brand charts.

Building more tools? Try our JavaScript tip calculator guide.

Or start from the first project in this series, our JavaScript QR code generator.

What Are Common Unit Converter Mistakes?

  • Using rounded factors, such as 2.2 for kilograms to pounds.
  • Treating temperature like a simple factor.
  • Showing 15 decimal places instead of rounding.
  • Mixing up US and UK gallons, which are different sizes.
  • Forgetting to handle empty or non-number input.

Write a short list of test cases, such as 1 inch to 2.54 centimeters, and check them after every change.

Which unit type will you add next?

  • Area
  • Volume
  • Speed
  • Digital storage
  • Not sure

Test Yourself

How many centimeters are in 1 inch, by definition?

  1. 2.5
  2. 2.54
  3. 2.56

The standards institute length page says the inch is exactly 25.4 millimeters, which is 2.54 centimeters.

Why can temperature not use a single factor?

  1. The scales have different zero points
  2. Temperature is not a unit
  3. JavaScript cannot multiply decimals

Celsius, Fahrenheit and kelvin start at different zero points, so you need formulas with an offset.

Frequently Asked Questions

How do I convert Celsius to Fahrenheit in JavaScript?

Multiply the Celsius value by 1.8 and add 32. To go the other way, subtract 32 and divide by 1.8.

What is the exact factor for kilograms to pounds?

One pound is exactly 0.45359237 kilograms. Divide kilograms by that number to get pounds.

How do I stop long decimals in results?

Use Number(value.toPrecision(10)) to keep 10 significant digits.

Is a mile exactly 1.609 kilometers?

No. It is exactly 1.609344 kilometers, based on the official definition.

Conclusion

Use a base unit table with exact factors, handle temperature with formulas, and round with toPrecision. Your converter will be accurate and easy to grow.

Editor’s Note

This guide is accurate as of December 3, 2026. Conversion factors come from the National Institute of Standards and Technology pages linked above. Code was tested in Node.js 22.

Spot an error in this article? Please contact us at support@digieh.com or read our Corrections Policy.

Keep exploring

Your next read is waiting

Found this useful?

Share this post
Avatar photo

Syed Wasif Raza

Syed Wasif Raza is the founder and editor of Digieh. He writes about health, food, lifestyle, news and sports in plain, easy English. Every guide he publishes is checked against official sources such as government and health agency pages. Connect with him on LinkedIn.

Articles: 1014

Leave a Reply

Your email address will not be published. Required fields are marked *