@@ -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