JavaScript中的百分比,然后从百分比反转为targetValue

时间:2019-06-12 03:09:47

标签: javascript

我正在尝试使用percentageDifference在一个地方计算baseValue + targetValue。然后在另一个地方,我用targetValue计算baseValue + percentageDifference。我得到的问题是,第一个计算给了我percentageDifference,当我将其用于第二个计算时,我得到的targetValue与第一个计算不同。

如何确保始终在所有计算中使用相同的3个值?

// Calculate targetValue

let baseValue = 50.8998;
let percentageDifference = 0.01;
let change = (percentageDifference / 100.0) * baseValue;
let targetValue = baseValue + change;

// Calculate percentageDifference

let baseValue = 50.8998;
let targetValue = 55.7878;
let percent = Math.abs(baseValue - targetValue) / baseValue;
let percentageDifference = percent * 100.0;

1 个答案:

答案 0 :(得分:0)

可以,删除Math.abs,简化数字

//calculate percentageDifference
let baseValue = 50;
let targetValue = 75;
let percent = (targetValue - baseValue) / baseValue;
let percentageDifference = percent * 100;
console.log('percentageDifference', percentageDifference, '. From', baseValue, 'to', targetValue)

//calculate targetValue
let baseValue1 = 50;
let percentageDifference1 = 50;
let change1 = (percentageDifference1 / 100) * baseValue1;
let targetValue1 = baseValue1 + change1;
console.log('targetValue', targetValue1)