TypeScript: Convert Fahrenheit to Celsius

1. Introduction

Converting between different temperature scales is a basic operation frequently required in various domains, from scientific computations to everyday applications. In this post, we'll dive into a TypeScript program that converts temperatures from Fahrenheit to Celsius.

2. Program Overview

The conversion from Fahrenheit to Celsius can be achieved using the formula (Fahrenheit - 32) * 5/9. In this blog post, we're going to create a function named fahrenheitToCelsius which accepts a temperature in Fahrenheit as its parameter and returns the converted temperature in Celsius.

3. Code Program

// Function to convert Fahrenheit to Celsius
function fahrenheitToCelsius(fahrenheit: number): number {
    return (fahrenheit - 32) * 5/9;
}

// Test the function
const fahrenheitTemperature = 77;
const celsiusTemperature = fahrenheitToCelsius(fahrenheitTemperature);
console.log(`${fahrenheitTemperature}°F is approximately equal to ${celsiusTemperature.toFixed(2)}°C.`);

Output:

77°F is approximately equal to 25.00°C.

4. Step By Step Explanation

1. We begin by defining the function fahrenheitToCelsius. It receives one argument: the temperature in Fahrenheit.

2. Within the function, we apply the conversion formula (Fahrenheit - 32) * 5/9 to compute the temperature in Celsius.

3. To demonstrate the function's utility, we then test it with a Fahrenheit value of 77.

4. The outcome, being the corresponding temperature in Celsius, is then displayed on the console. For precision, we use the toFixed(2) method to round the Celsius value to two decimal places.

Comments