0

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 = %

I have a console log for the original number as console.log(data.Results.Data[115].DataValue, "First") which shows 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

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. I am expecting to show 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")
}
j3ff
  • 5,719
  • 8
  • 38
  • 51
kurtixl
  • 419
  • 4
  • 17

1 Answers1

1

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})`)
    }
CherryDT
  • 25,571
  • 5
  • 49
  • 74