on codepen at https://codepen.io/kschuljak/pen/rNYmEBO
- converts between Celsius, Fahrenheit, and Kelvin
- displays converted temperature rounded to two decimal places and with appropriate unit
- displays error when no number is entered to convert
- if both conversion options are the same (ex, Celsius to Celsius) the number entered is the number displayed
function roundTwoDecimals(x) {
let rounded = Number((Math.abs(x) * 100).toPrecision(15));
return Math.round(rounded) / 100 * Math.sign(x);
}
const convertTemp = (x, inputUnitSelected, outputUnitSelected) => {
// ... (code omitted for example - error handling if x is NaN)
// selects correct conversion based on entered values
// assigns the correct unit to display on result
if (inputUnitSelected == "Kelvin" && outputUnitSelected == "Celsius") {
convertedOutputTemp = (x - 273.15);
unit = "°C";
} else if (inputUnitSelected == "Kelvin" && outputUnitSelected == "Fahrenheit") {
convertedOutputTemp = (1.8 * (x - 273) + 32);
unit = "°F";
// ... (etc - code omitted for example)
// if input and output unit are the same, return entered value (rounded to two decimals)
// entered value displayed with appropriate unit
} else if (inputUnitSelected == outputUnitSelected) {
convertedOutputTemp = x;
if (outputUnitSelected == "Fahrenheit") {
unit = "°F";
} // ... (etc - code omitted for example)
} else {
convertedOutputTemp = "please double check conversion options";
return;
}
let answer = roundTwoDecimals(convertedOutputTemp);
return answer + ' ' + unit;
}