JavaScript toFixed Question | XM Community
Skip to main content
I am trying to adapt some code from this thread so that I can pull the numeric value from a question and post it to an embedded data value with always having 2 decimal places (think US currency).



> ```

> Qualtrics.SurveyEngine.addOnload(function() {

> var score = parseFloat("${gr://SC_cvbYKS7ZMqwXmgR/Score}");

> score = Math.round(score * 10) / 10;

> Qualtrics.SurveyEngine.setEmbeddedData("score1", score.toFixed(1));

> });

> ```



I've tried the following codes, on UnLoad, and doesn't seem to work. Any suggestions?



> ```

> var Q8 = ("${q://QID8/ChoiceTextEntry/Value}");

> var Q8 = Q8.toFixed(2);

>

>Qualtrics.SurveyEngine.setEmbeddedData("score.Q8", Q8);

>```

and



> ```

> var Q8 = ("${q://QID8/ChoiceTextEntry/Value}");

>

>Qualtrics.SurveyEngine.setEmbeddedData("score.Q8", Q8.toFixed(2);

>```
You need to convert the piped string to a number to use toFixed.

```

Qualtrics.SurveyEngine.addOnload(function() {

var Q8 = parseFloat("${q://QID8/ChoiceTextEntry/Value}");

Qualtrics.SurveyEngine.setEmbeddedData("score.Q8", Q8.toFixed(2));

});

```

I'm confused about the Unload comment. I'm assuming it is a typo.
@TomgG - Thanks for your help, as always!



So I've tried the code in all 3 sections:

* Qualtrics.SurveyEngine.addOnload

* Qualtrics.SurveyEngine.addOnReady

* Qualtrics.SurveyEngine.addUnload



The last one is what I mean with 'UnLoad'. I was thinking that if I wanted to put the code in the same text entry question, then(QID8), then I'd need to do that on UnLoad. It was a bit of shot in the dark.



I've tried adding your code to addOnLoad of QID8 and the question on another page and in both instance I get score.Q8 = NaN.



Any thoughts?
NaN means "Not a Number". So, the thing you are piping isn't parsing as a number. For example, if the first character of the string isn't a digit it won't parse as a number.



Unload won't work. If you need to set it before going to the next page use addOnPageSubmit and retrieve the value directly from the input element.
> @TomG said:

> NaN means "Not a Number". So, the thing you are piping isn't parsing as a number. For example, if the first character of the string isn't a digit it won't parse as a number.

>

> Unload won't work. If you need to set it before going to the next page use addOnPageSubmit and retrieve the value directly from the input element.

>

>



There must have been something lingering in my test project that interfered with this because I created a new survey and recreated the code and everything works.

Leave a Reply