I want you to implement a JavaScript function that converts Fahrenheit to Celsius, as…
- User
I want you to implement a JavaScript function that converts Fahrenheit to Celsius, as well as a function that does the opposite. The code should be functional and modular. Reuse code between both functions, by making common functions, where it makes sense. Can you write the code please?
- Assistant
Sure, I can help you with that. Here is a basic implementation that satisfies your request:
// Common function to round the result to 2 decimal places function roundToTwoDecimals(num) { return Math.round((num + Number.EPSILON) * 100) / 100; } // Function to convert Fahrenheit to Celsius function fahrenheitToCelsius(fahrenheit) { var celsius = (fahrenheit - 32) * (5/9); return roundToTwoDecimals(celsius); } // Function to convert Celsius to Fahrenheit function celsiusToFahrenheit(celsius) { var fahrenheit = (celsius * (9/5)) + 32; return roundToTwoDecimals(fahrenheit); }In this code, the
fahrenheitToCelsiusfunction accepts a number (representing degrees Fahrenheit) and converts it to Celsius using the standard formula. ThecelsiusToFahrenheitfunction does the opposite.Both functions call the
roundToTwoDecimalsfunction to ensure the returned value is rounded to two decimal places. This function uses a common trick to avoid precision errors in floating point arithmetic by adding a very small number (Number.EPSILON) before rounding.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)