Skip to content

Commit bdaef78

Browse files
Merge pull request steam-bell-92#1669 from akshara200829-lgtm/fix/unit-converter-decimal-formatting
fix: format conversion results to 6 decimals, strip trailing zeros
2 parents 085f21b + 015704d commit bdaef78

1 file changed

Lines changed: 16 additions & 4 deletions

File tree

web-app/js/projects/unit-converter.js

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,15 @@ function initUnitConverter() {
164164
}
165165

166166

167+
// ==== FORMATTING ====
168+
169+
function formatResult(value) {
170+
if (isNaN(value) || value === null) return "Invalid input";
171+
// Round to 6 decimal places, then strip trailing zeros
172+
return parseFloat(value.toFixed(6)).toString();
173+
}
174+
175+
167176
// ==== EVENT LISTENERS ====
168177

169178
document.getElementById("from").addEventListener("input", convert);
@@ -220,23 +229,26 @@ function initUnitConverter() {
220229
else if (inpOpt === "k") {
221230
tempVal = inpVal - 273.15;
222231
}
232+
let tempOut;
223233
if (outOpt === "c") {
224-
outVal.value = tempVal;
234+
tempOut = tempVal;
225235
}
226236
else if (outOpt === "f") {
227-
outVal.value = (tempVal * 9 / 5) + 32;
237+
tempOut = (tempVal * 9 / 5) + 32;
228238
}
229239
else if (outOpt === "k") {
230-
outVal.value = tempVal + 273.15;
240+
tempOut = tempVal + 273.15;
231241
}
242+
outVal.value = formatResult(tempOut);
232243
result.value = `${inpVal} ${fromName} = ${outVal.value} ${toName}`
233244
return;
234245
}
235246

236247
// OTHER CONVERSIONS
237248

238249
const base = inpVal * units[currentCategory][inpOpt].factor;
239-
outVal.value = base / units[currentCategory][outOpt].factor;
250+
const rawOut = base / units[currentCategory][outOpt].factor;
251+
outVal.value = formatResult(rawOut);
240252

241253
result.value = `${inpVal} ${fromName} = ${outVal.value} ${toName}`
242254

0 commit comments

Comments
 (0)