syntax issue with addition in javascript - javascript

I am making some addition and substraction in my javascript, but I have strange results, I don't understanf whats wrong in my syntax:
var dy, i,diff;
dy=(lines_extrema[0]-lines_extrema[1])
for(i=1;i<=(narrow+1);i++){
// Coordinates
if(i==1) diff=(-lines_extrema[1]);
else diff=(diff+lines[(0+3*(i-2))]);
}
lines and lines_extrema are read through get methods and are real.
dy is fine, I have a real.
diff is fine for i=0 and them it returns things like that "20.9603-10.9".
What's wrong in my syntax?
Thanks

You are doing operation on string variables instead of numbers, so the addition is actually a concatenation.
To convert string to numbers, prefix them with "+". Example:
var extrema0 = +lines_extrema[0];
var extrema1 = +lines_extrema[1];
then use extrema0 and extrema1 to add/substract.

Related

Correctly format a whole number to a 2 decimal places output in JS but put 0 in front [duplicate]

I have a script which returns a price for a product. However, the price may or may not include trailing zeros, so sometimes I might have 258.22 and other times I might have 258.2. In the latter case, I need to add the trailing zero. How would I go about doing this?
You can use javascript's toFixed method (source), you don't need jQuery. Example:
var number = 258.2;
var rounded = number.toFixed(2); // rounded = 258.20
Edit: Electric Toolbox link has succumbed to linkrot and blocks the Wayback Machine so there is no working URL for the source.
Javascript has a function - toFixed - that should do what you want ... no JQuery needed.
var n = 258.2;
n.toFixed (2); // returns 258.20
I don't think jQuery itself has any string padding functions (which is what you're looking for). It's trivial to do, though:
function pad(value, width, padchar) {
while (value.length < width) {
value += padchar;
}
return value;
}
Edit The above is great for strings, but for your specific numeric situation, rosscj2533's answer is the better way to go.

How to parseInt or ParseInt embedded data with TypeScript in Qualtrics?

Even when I save an integer to embedded data earlier in the survey flow (in previous blocks on different screens), I am not able in Javascript to get the embedded data value, ensure it is parsed as a number/integer, then use it in a loop. Is this something about TypeScript? I didn't see anything about parseInt or ParseInt in the TypeScript documentation.
For example, suppose I do the following:
// Draw a random number
var x = Math.floor(Math.random() * 5);
// Save it in embedded data
Qualtrics.SurveyEngine.setEmbeddedData("foo", x);
// In a later block on a different screen, get the embedded data as an integer
var x_new = "${e://Field/foo}"; // not an int
var x_new = parseInt("${e://Field/foo}"); // doesn't work
var x_new = ParseInt("${e://Field/foo}"); // doesn't work
// Loop using x_new:
for(i = 0; i < x_new; i++) {
console.log(i)
}
Any idea why this isn't working? Perhaps I just don't know how to parseint().
In "normal" JS runtime system, we have parseInt function, the function gets a string (like number string) as a parameter. In this env, we don't support your syntax - "${e://Field/foo}", because it is not a "number string".
In Qualtrics system environment they have parseInt too, but they support their custom syntax "${e://Field/foo}" to get EmbeddedData.
Make sure that your code is running on Qualtrics system environment.
ParseInt is just turning your string into an integer.
Look at the demo below.
let myVar = "${e://Field/foo}"; // This is a string
console.log(myVar); // This prints a string
console.log(parseInt(myVar)); // This prints "NaN", i.e. Not a Number, because the string isn't a representation of a number.

Why do I get undefined here?

function myFunc() {
var word = document.getElementById("Text1").value;
var num = parseInt(document.getElementById("Text2").value);
var numstr = num.split(",");
var wordstr = word.split("");
for (i = 0; i < word.length; i++) {
}
document.getElementById("myDiv").innerHTML += (wordstr[(numstr[i])-1]);
}
did I parseInt incorrectly? I've tried toString(), with ParseInt it doesn't do anything and without it I get 'undefined'
The parseInt() function parses a string and returns an integer.
You check your input with id "Text2" and show your HTML here to clearify the issue.
Without knowing more about your problem, it looks like you are misunderstanding how parseInt() works. Despite the misleading name, it will read your string character by character, attempting to create an integer. It will stop as soon as it finds a character that can't be part of an integer.
If you pass it "1,2,3,4" then it will read the 2 fine, but as a comma cannot be parsed as part of an integer, it will return the number 2. It doesn't make sense to call split on a number.
As others have said, you really need to give us more details for us to be able to help, but I suspect a large part of the problem is not understanding what some of these functions do.
Maybe you could explain what you're trying to achieve, then we can help you get there. Right now, your code isn't clear enough without extra information.

I need help writing a basic return decimal from string function in Javascript

I have scoured the web for an hour-and-a-half looking for a working, simple string-to-decimal function, and have been depressingly failed. The mentioned string is comprised of letters and numbers. This is meant for a cipher. I would like something like this...
function ConvertDec(str){
//do conversion
return decVal;
}
Were it would be used as such...
decSeed = ConvertDec(seed);
decUserString = ConvertDec(strVal);
These values would then be multiplied to get a full value, which would later be decrypted.
Here's the basics
var str = "123.45";
var dec = parseFloat(str);
console.log(dec); // 123.45
Read more about parseFloat here

JQuery adding number value

can someone help me debug this please???
i'm really don't know whats wrong with my code...
i'm trying to add number value to another number value.... but it does not work as i expected...instead it just add the number as a string.
Here is my demo:
(already solved)
and here is the js code:
$(document).ready(function(){
$("#map").click(function(e){
var x = parseInt((e.pageX - this.offsetLeft)) - parseInt("140");
var y = parseInt((e.pageY - this.offsetTop)) - parseInt("140");
var coor = $("#map").css("background-position").split(" ");
var cx = parseInt(coor[0].replace("px",""));
var cy = parseInt(coor[1].replace("px",""));
$("#map").stop().animate({"backgroundPosition": x+cx+" "+y+cy},"slow");
alert("X:"+x+", CX: "+cx+"\n Y:"+y+", CY:"+cy+"\n Background-pos:"+$("#map").css("background-position"));
});
});
please tell me what's wrong with it...
Put parentheses () around your arithmetic operations.
$("#map").stop().animate({"backgroundPosition": (x+cx)+" "+(y+cy)},"slow");
Otherwise, adding the whitespace string will force the JS to concatenate your numbers as a string.
Fiddle example
In your animate-Statement towards the end you set background position to:
x+cx+" "+y+cy
This is interpreted as a string, because the four +-operations are interpreted equally. You do, really, concatinate a string (" "). Thus, the entire result of this expression becomes a string and the addition is no longer an addition but a concat.
However, if you capsulate the math into parenthesis, then you should be fine. Your second-last line becomes:
$("#map").stop().animate({"backgroundPosition": (x+cx)+" "+(y+cy)},"slow");
(note the extra brackets around x+cx)
Isn't it ?
var x = parseInt((e.pageX - $(this).offset().left)) - parseInt("140");
var y = parseInt((e.pageY - $(this).offset().top)) - parseInt("140");
The following works for me:
$("#map").click(function(e){
alert(e.pageX);
alert(this.offsetLeft);
alert(parseInt(e.pageX)-parseInt(this.offsetLeft));

Categories