Health and baby apps keep showing temperatures in both scales, and the conversion is the easy part. The parts that go wrong are the display rounding and the labels ("is 99.5 a fever?"). Here is the small amount of code that gets both right, plus a free chart of every reading from 95.0 to 106.0 °F you can drop into a test suite.
The conversion, and the floating point trap on the way back
const fToC = (f) => ((f - 32) * 5) / 9;
const cToF = (c) => (c * 9) / 5 + 32;
fToC(98.6); // 37
fToC(100.4); // 38
cToF(36.6); // 97.88000000000001
cToF(39.4); // 102.91999999999999
Fahrenheit to Celsius happens to come out clean for every 0.1 °F step between 95 and 106. The other direction does not: 15 of the 62 Celsius readings between 35.0 and 41.1 print with floating point noise. Round for display only, and keep the raw number for comparisons:
const round1 = (x) => Math.round(x * 10) / 10;
round1(cToF(36.6)); // 97.9
round1(fToC(103)); // 39.4
The labels
The usual mistake is a single "fever above 99" check. The CDC counts a fever from 100.4 °F (38 °C), and the normal adult range is roughly 97 to 99 °F (36.1 to 37.2 °C), so there is a band in between that is raised but not a fever:
function classify(f) {
if (f < 95) return "Hypothermia";
if (f < 97) return "Below normal";
if (f < 99) return "Normal";
if (f < 100.4) return "Raised, not a fever";
if (f < 106) return "Fever";
return "Very high fever";
}
classify(98.6); // "Normal"
classify(99.5); // "Raised, not a fever"
classify(100.4); // "Fever"
Classify on the value the user entered (or on Fahrenheit computed from it), not on a rounded display string. If someone enters 38.0 °C, cToF(38) is exactly 100.4 in JavaScript, so the boundary holds, but comparing rounded strings is how off-by-0.1 bugs get in.
A dataset to test against
I put every reading from 95.0 to 106.0 °F in 0.1 steps (111 rows) into a CSV and JSON file with the Celsius value, the label and a short note:
- Repo: https://github.com/Shehrii/body-temperature-chart
- Printable chart: https://shehrii.github.io/body-temperature-chart/
| °F | °C | Reading |
|---|---|---|
| 96.8 | 36 | Below normal |
| 98.6 | 37 | Normal |
| 99.5 | 37.5 | Raised, not a fever |
| 100.4 | 38 | Fever |
| 103 | 39.44 | Fever |
A table-driven test is then a loop:
import rows from "./body-temperature-f-to-c.json" with { type: "json" };
for (const r of rows) {
console.assert(Math.abs(fToC(r.fahrenheit) - r.celsius) < 0.01, r.fahrenheit);
console.assert(classify(r.fahrenheit) === r.reading, r.fahrenheit);
}
If you only need a single value, each common reading has its own page on Unit Equals, for example 100.4 °F in Celsius or 98.6 °F in Celsius, and the Fahrenheit to Celsius converter covers the rest.
Not medical advice: the thresholds follow the CDC fever definition, and a fever in a baby under 3 months, one above 103 °F (39.4 °C), or one that lasts more than a few days is a reason to call a doctor.
Data is CC BY 4.0; credit "Body temperature data: Unit Equals".
Top comments (0)