I am trying to load an existing answer and then add a number to it. The answerTotal variable has been set to the value of the recorded answer.

This then should be increasing by 12.5 each time the if statement actions. The problem is that this is not what is happening.

The number is being added on to the end of the loaded answer, for example if the load answer is 25, the output would be 2512.5 when it should be 37.5.

I have seen answers on here mentioning parseInt but it either doesnt work or im not using it correctly. parse answer

Here is what I have at the moment:

var answerTotal = 0;

window.parent.LoadAnswerReturned = function (Reference, Value) {

    answerTotal = Value;

}
setTimeout(function(){
  window.parent.LoadAnswer('TEST');
}, 100);


function checkAnswer(clicked) {
 if(...){
    ...
    answerTotal += 12.5
 }
}

Please let me know if any more information is needed. Cheers.

3 Answers

1
LuSchink On Best Solutions

You should parse your float variable, so you ensure you are using float variables:

answerTotal = parseFloat(answerTotal) + 12.5;
2
Maheer Ali On

It seems that the variable answerTotal is a string. You need to convert it to number using Unary Plus and then add it other number.

function checkAnswer(clicked) {
 if(...){
    ...
    answerTotal = +answerTotal + 12.5
 }
}
2
Dacre Denny On

The unexpected result is because by the type of the variable data that is string rather than number. This in turn means that string addition is performed:

"25" + "12.5" = "2512.5"

Instead, you should update you code to ensure arithemtic addition is performed instead:

function checkAnswer(clicked) {
 if(...){
    ...
    /* Use parseFloat to ensure two numbers are added, rather than a string
    and a number */
    answerTotal = Number.parseFloat(answerTotal) + 12.5;
 }
}