- Instant help with your JavaScript coding problems

Convert Fahrenheit to Celsius in JavaScript

Question:
How to convert Fahrenheit to Celsius in JavaScript?
Answer:
function fahrenheitToCelsius(fahrenheitValue) {
    return (fahrenheitValue - 32) * 5 / 9;
}
Description:

Most of the world measures temperature in degrees Celsius, but the United States still uses Fahrenheit. The conversion formula is:

X °F = (X − 32) * 5/9 °C

With this formula, you can now easily write a conversion function in JavaScript, the basic version of which looks like this:

function fahrenheitToCelsius(fahrenheitValue) {
    return (fahrenheitValue - 32) * 5 / 9;
}

In reality, a precision result is usually not needed, but an integer value would be fine. Therefore, you may want to round the result using Math.round .

function fahrenheitToCelsius(fahrenheitValue) {
    return Math.round((fahrenheitValue - 32) * 5 / 9);
}

You can further refine the conversion function by also specifying the precision as a parameter. Since an integer value is sufficient in most cases, it is recommended to specify 0 decimal places as default.

function fahrenheitToCelsius(fahrenheitValue, precision = 0) {
    const celsiusValue = (fahrenheitValue - 32) * 5 / 9;
    const precisionFactor = Math.pow(10, precision);
    return Math.round(celsiusValue * precisionFactor) / precisionFactor;
}

Usage example:

console.log('32°F is ' + fahrenheitToCelsius(32) + '°C');
console.log('75°F is ' + fahrenheitToCelsius(75) + '°C');
console.log('75°F is ' + fahrenheitToCelsius(75,2) + '°C');

The output is:

32°F is 0°C
75°F is 24°C
75°F is 23.89°C

If you use TypeScript, the TypeScript version looks like this:

function fahrenheitToCelsius(fahrenheitValue: number, precision = 0) : number {
    const celsiusValue = (fahrenheitValue - 32) * 5 / 9;
    const precisionFactor = Math.pow(10, precision);
    return Math.round(celsiusValue * precisionFactor) / precisionFactor;
}

 

Share "How to convert Fahrenheit to Celsius in JavaScript?"