Convert Celsius to Fahrenheit in JavaScript
Beginner · 4 min read
Weather apps, thermostats and recipe sites often show temperatures in both Celsius and Fahrenheit. Most of the world uses Celsius, the United States uses Fahrenheit, and a lot of software has to switch between them. In this tutorial you will write both conversions and learn something useful about decimals along the way.
You will write toFahrenheit(c) and toCelsius(f), then check that converting a temperature there and back gives you the number you started with. You need to know what a function is and how arithmetic works in JavaScript. Arrow functions are explained below.
The two formulas
On the Celsius scale water freezes at 0 and boils at 100. On the Fahrenheit scale it freezes at 32 and boils at 212. So 100 Celsius steps cover the same range as 180 Fahrenheit steps, which is a ratio of 9 to 5.
Fahrenheit = Celsius × 9 / 5 + 32
Celsius = (Fahrenheit − 32) × 5 / 9
To go one way you scale, then shift by 32. To go back you undo the shift first, then undo the scale.
Arrow functions
A short function can be written as an arrow function. These two do the same thing:
function double(n) { return n * 2; }
const doubleArrow = (n) => n * 2;
console.log(double(4), doubleArrow(4)); // 8 8
The arrow version puts the input in brackets, then =>, then the value to return. With no curly braces, the value after the arrow is returned automatically.
Here is the exercise. Try it on your own first if you like, or follow the steps below.
11 Convert between Celsius and Fahrenheit
easyConvert a temperature from Celsius to Fahrenheit and back. Show that a round trip returns the original value.
Stuck? Three hints, smallest first
- 1. Fahrenheit is
c * 9 / 5 + 32; Celsius is(f - 32) * 5 / 9. - 2. A round trip may not be exactly equal because of floating point. Compare with a small tolerance.
- 3. -40 is the one temperature where both scales read the same. It makes a good test.
Step 1: Celsius to Fahrenheit
const toFahrenheit = (c) => (c * 9) / 5 + 32;
console.log(toFahrenheit(0)); // 32
console.log(toFahrenheit(100)); // 212
Freezing and boiling are the two numbers everyone knows, so they make the first test.
Step 2: try more temperatures
Loop over a few values. A template literal (text between backticks) drops each number into a sentence with ${ }.
for (const c of [-40, 0, 37, 100]) {
console.log(`${c}°C = ${toFahrenheit(c)}°F`);
}
This prints:
-40°C = -40°F
0°C = 32°F
37°C = 98.6°F
100°C = 212°F
Look at the first line. −40 is the one temperature where both scales show the same number. It makes a good test, because a formula with a mistake in it rarely gets −40 right by luck.
Step 3: Fahrenheit back to Celsius
Undo the 32 first, then scale by 5/9. The brackets around f - 32 make sure the subtraction happens before the multiplication.
const toCelsius = (f) => ((f - 32) * 5) / 9;
console.log(toCelsius(212)); // 100
console.log(toCelsius(32)); // 0
A common slip is writing f - 32 * 5 / 9. JavaScript multiplies before it subtracts, so that takes 17.77… away from f and gives the wrong answer.
Step 4: there and back
If both formulas are right, converting a temperature to Fahrenheit and back should return the same number. Try it with a few:
console.log(toCelsius(toFahrenheit(36.6))); // 36.6
console.log(toCelsius(toFahrenheit(15.7))); // 15.699999999999998
console.log(toCelsius(toFahrenheit(15.7)) === 15.7); // false
36.6 comes back exactly, but 15.7 doesn't. The formulas are right. The problem is that computers store decimals in binary, and most decimals, like 15.7, can't be stored exactly. Multiplying and dividing by 9 and 5 can add a tiny error, so the result may be a hair away from where you started. Which numbers survive the trip is hard to predict, so code shouldn't rely on it.
Step 5: compare with a tolerance
When decimals and division are involved, ask "are these close enough?" instead of "are these exactly equal?". Math.abs gives the size of the gap without its sign, and a tolerance like 1e-9 (0.000000001) says how close counts as equal.
const close = (a, b, tolerance = 1e-9) => Math.abs(a - b) < tolerance;
console.log(close(toCelsius(toFahrenheit(15.7)), 15.7)); // true
console.log(close(toCelsius(toFahrenheit(36.6)), 36.6)); // true
tolerance = 1e-9 is a default value: if you leave out the third argument, it uses that. The close check passes for both numbers, the one that came back exactly and the one that didn't. That is the point: you don't need to know in advance which kind you have.
The full solution
The complete answer has both conversions and prints the four sample temperatures. Then it takes 36.6 there and back and prints the result, an exact comparison and the close check. Press Run to see it, then try changing 36.6 to 15.7 and run it again.
const toFahrenheit = (c) => (c * 9) / 5 + 32;
const toCelsius = (f) => ((f - 32) * 5) / 9;
for (const c of [-40, 0, 37, 100]) {
console.log(`${c}°C = ${toFahrenheit(c)}°F`);
}
// A round trip should return the original, but floating point means "should"
// needs a tolerance rather than an equals sign.
const close = (a, b, tolerance = 1e-9) => Math.abs(a - b) < tolerance;
const roundTrip = toCelsius(toFahrenheit(36.6));
console.log('36.6 there and back:', roundTrip);
console.log('exactly equal?', roundTrip === 36.6);
console.log('close enough? ', close(roundTrip, 36.6));
Output
6 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 6 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('freezing', toFahrenheit(0), 32);
test('boiling', toFahrenheit(100), 212);
test('body temperature', Number(toFahrenheit(37).toFixed(1)), 98.6);
test('the scales meet at -40', toFahrenheit(-40), -40);
test('back the other way', toCelsius(212), 100);
test('a round trip is close, not exact', close(roundTrip, 36.6), true);
The round-trip assertion is the interesting one. toCelsius(toFahrenheit(36.6)) is not exactly 36.6, because dividing by 5 and 9 cannot be done exactly in binary. That is why the close helper exists: for any calculation involving division, compare within a tolerance rather than with ===.
Common mistakes
- Missing brackets in
toCelsius.f - 32 * 5 / 9subtracts too late. Write(f - 32) * 5 / 9. - Comparing decimal results with
===. Tiny binary errors make it false. Use a tolerance. - Using 9/5 in both directions. Going back to Celsius uses 5/9, the upside-down fraction.
Try it yourself
- Add Kelvin:
toKelvin(c)isc + 273.15. What is absolute zero, 0 K, in Fahrenheit? - Round the Fahrenheit result to one decimal place for display with
toFixed(1). - Print a table from −10°C to 40°C in steps of 5, with the Fahrenheit value next to each.