[英]Percentage difference between two numbers equals NaN - JavaScript
I'm calculating the difference between the two numbers I am getting from an array.我正在计算从数组中获得的两个数字之间的差异。 I would like to get the percentage difference between the two, so my logic behind it is:
Original number / New Number * 100 = %
我想得到两者之间的百分比差异,所以我背后的逻辑是:
Original number / New Number * 100 = %
I have a console log for the original number as console.log(data.Results.Data[115].DataValue, "First")
which shows 1,378,637.7我有一个原始数字的控制台日志为
console.log(data.Results.Data[115].DataValue, "First")
显示 1,378,637.7
I have another console log for the new number as console.log(data.Results.Data[116].DataValue, "Second")
which equals to 1,470,393.0我有另一个新号码的控制台日志为
console.log(data.Results.Data[116].DataValue, "Second")
等于 1,470,393.0
I am now trying to declare a variable that would equal the percentage between these two values.我现在试图声明一个等于这两个值之间百分比的变量。
let perChangeOne = data.Results.Data[116].DataValue / data.Results.Data[115].DataValue * 100 console.log(perChangeOne, "%%")
When the console.log for perChangeOne equals NaN.当 perChangeOne 的 console.log 等于 NaN 时。 I am expecting to show 106.7
我期待显示 106.7
function drawPercentageDifference(data) {
let perChangeOne = data.Results.Data[116].DataValue / data.Results.Data[115].DataValue * 100
console.log(perChangeOne, "%%")
console.log(data.Results.Data[116].DataValue, "First")
console.log(data.Results.Data[115].DataValue, "Second")
}
You values are probably strings, and due to the ,
they can't be coerced to a number.您的值可能是字符串,并且由于
,
它们不能被强制为数字。
You need to remove the ,
.您需要删除
,
。 Even though it's not strictly necessary, I'd then convert to a number explicitly as well:即使这不是绝对必要的,我也会明确地转换为数字:
function drawPercentageDifference(data) {
const numerator = Number(data.Results.Data[116].DataValue.replace(/,/g, ''))
const denominator = Number(data.Results.Data[115].DataValue.replace(/,/g, ''))
const percentage = 100 * numerator / denominator
console.log(`${percentage} % (${numerator} / ${denominator})`)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.