使用toFixed问题在javascript中将米转换为英尺,反之亦然

问题描述

我正在尝试生成从米到英尺单位转换,反之亦然。我已经多次看到这个问题,但我没有找到一个答案,为什么使用 .toFixed(1) 在所有情况下都不能计算到小数点后一位。我知道 JavaScript 对这些东西很挑剔,我仍在努力理解它。我可能走错了路,所以欢迎提供任何建议。

1 米换算成英尺没问题,但 1 英尺换算成米,结果是小数点后 17 位。

如果您尝试将 1.1 米转换为英尺,那很好,反之亦然,您会得到 17 位小数。

当您开始将 1.2 米转换为英尺时,情况会变得更糟。

我制作了一个简单的片段来说明我的问题。如果有人可以帮助我解决问题,以便结果只保留小数点后一位,我将不胜感激。

    select shiwangini_unq();  ----null
@H_502_17@

解决方法

您在 toFixed 上调用 conversion,但您想在计算结果时调用它:(unitFoot1 * conversion).toFixed(1)

// 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 Metre is equal to',(unitFoot1_1 * conversion).toFixed(1),(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 Metre is equal to',(unitFoot1_2 * conversion).toFixed(1),(unitMetre1_2 / conversion).toFixed(1),'Metres')

我知道 JavaScript 对这些东西很挑剔

这与 JavaScript 无关,但如果您使用浮点数进行计算,则会发生在任何语言中。