I'm trying to produce a unit conversion from metres to feet and vice versa. I've seen this question asked many times, but what I haven't found is an an answer to why using the .toFixed(1) does not calculate to 1 decimal place in all cases. I know JavaScript is finicky with such things, and I'm still trying to understand it. I've probably gone down the wrong route, so any advice is welcome.
It's fine for converting 1 metre to feet, but converting 1 foot to metres, the result is to 17 decimal places.
If you try converting 1.1 metres to feet that's fine but vice versa you get 17 decimal places.
It's gets even worse when you start to convert 1.2 metres to feet.
I've produced a simple snippet to illustrate my issue. If there's anyone who can help with my solution so that the result is only ever 1 decimal place, I'd be grateful.
// Converting Metres to Feet and Feet to Metres
const conversion = 3.281
console.log('--- Conversion of 1 Metre / 1 Foot ---')
let unitFoot1 = 1
let unitMetre1 = 1
console.log('1 Metre is equal to', unitFoot1 * conversion.toFixed(1), 'Feet')
console.log('1 Foot is equal to', unitMetre1 / conversion.toFixed(1), 'Metres')
console.log('--- Conversion of 1.1 Metres / 1.1 Feet ---')
let unitFoot1_1 = 1.1
let unitMetre1_1= 1.1
console.log('1.1 Metre is equal to', unitFoot1_1 * conversion.toFixed(1), 'Feet')
console.log('1.1 Foot is equal to', unitMetre1_1 / conversion.toFixed(1), 'Metres')
console.log('--- Conversion of 1.2 Metres / 1.2 Feet ---')
let unitFoot1_2 = 1.2
let unitMetre1_2= 1.2
console.log('1.2 Metres is equal to', unitFoot1_2 * conversion.toFixed(1), 'Feet')
console.log('1.2 Foot is equal to', unitMetre1_2 / conversion.toFixed(1), 'Metres')
You are calling
toFixed
onconversion
, but you want to call it at the result of your calculations:(unitFoot1 * conversion).toFixed(1)
.That is not related to JavaScript but happens in any language if you calculate with floating-point numbers.