JavaScript
// Formula: Celsius = (Fahrenheit - 32) * 5/9
let fahrenheit = 98.6;
let celsius = (fahrenheit - 32) * 5 / 9;
console.log(`${fahrenheit}°F = ${celsius.toFixed(2)}°C`);
// Function version
function fahrenheitToCelsius(f) {
return (f - 32) * 5 / 9;
}
let temp1 = fahrenheitToCelsius(32); // Freezing point
let temp2 = fahrenheitToCelsius(212); // Boiling point
let temp3 = fahrenheitToCelsius(98.6); // Body temperature
console.log(`32°F = ${temp1}°C`);
console.log(`212°F = ${temp2}°C`);
console.log(`98.6°F = ${temp3.toFixed(2)}°C`);Output
98.6°F = 37.00°C 32°F = 0°C 212°F = 100°C 98.6°F = 37.00°C
This program demonstrates temperature conversion and working with decimal numbers.
Temperature Conversion Formula
Celsius = (Fahrenheit - 32) × 5/9
Key Points:
- Subtract 32 from Fahrenheit
- Multiply by 5/9 (or 0.5556)
- Result is in Celsius
Common Temperatures:
- Freezing: 32°F = 0°C
- Boiling: 212°F = 100°C
- Body temp: 98.6°F = 37°C
- Room temp: 68°F = 20°C
Working with Decimals
JavaScript handles floating-point arithmetic:
javascriptlet result = (98.6 - 32) * 5 / 9; // Result: 37.00000000000001 (floating point precision)
Rounding Methods
-
toFixed(n): Rounds to n decimal places, returns string
javascript(37.00001).toFixed(2); // "37.00" -
Math.round(): Rounds to nearest integer
javascriptMath.round(37.6); // 38 -
Math.floor(): Rounds down
javascriptMath.floor(37.9); // 37 -
Math.ceil(): Rounds up
javascriptMath.ceil(37.1); // 38
Function Approach
Creating a reusable function:
javascriptfunction fahrenheitToCelsius(f) { return (f - 32) * 5 / 9; }
Benefits:
- Reusable code
- Clear purpose
- Easy to test
- Can be called multiple times
Reverse Conversion
Celsius to Fahrenheit:
javascriptfunction celsiusToFahrenheit(c) { return (c * 9 / 5) + 32; }