Convert Fahrenheit to Celsius in JavaScript
function fahrenheitToCelsius(fahrenheitValue) {
return (fahrenheitValue - 32) * 5 / 9;
}
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;
}
- Convert Fahrenheit to Celsius in JavaScript
- Convert kilometers to miles in JavaScript
- Convert Map values to array in JavaScript
- Round a number to 2 decimal places in JavaScript
- Convert string to int in JavaScript
- Convert snake case to camel case in JavaScript
- Capitalize words in a string using JavaScript
- Convert string to kebab case in JavaScript
- Convert string to character array in JavaScript
- Convert camel case to snake case in JavaScript
- Remove accents from a string in JavaScript
- Convert a string to sentence case in JavaScript
- Convert string to title case in JavaScript
- Convert string to snake case in JavaScript
- Convert string to pascal case in JavaScript
- Convert string to camel case in JavaScript
- Convert string to uppercase with JavaScript
- Convert a float number to integer in JavaScript
- Convert object to JSON string in JavaScript
- Parse JSON string in JavaScript
- convert number to string in JavaScript