1

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.

JJJ
  • 32,902
  • 20
  • 89
  • 102
Eddie
  • 390
  • 3
  • 13
  • 1
    You might want to check what type the parameter `Value` in `LoadAnswerReturned` has and make sure this is already an integer. – empiric May 13 '19 at 08:53
  • 1
    [I think there's a jQuery plugin for that](https://i.stack.imgur.com/ssRUr.gif) – JJJ May 13 '19 at 09:28

3 Answers3

2

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
 }
}
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
2

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;
 }
}
Dacre Denny
  • 29,664
  • 5
  • 45
  • 65
1

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

answerTotal = parseFloat(answerTotal) + 12.5;
Lu Chinke
  • 622
  • 2
  • 8
  • 27