Menu

Body temperature in JavaScript: F/ C conversion, rounding and the fever line
📰

Body temperature in JavaScript: F/ C conversion, rounding and the fever line

DEV Community: javascript·Shahryar Ahmad·15 days ago
#HV32dK4m
#devtojavascript#devto#dev#fever#fahrenheit
Long article (656 words) — no AI summary yet.
Reading 0:00
15s threshold

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

Enter fullscreen mode

Exit fullscreen mode

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 .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.