multiply string in js which is both multiplier and multiplication operator - javascript

I want to transform the example string "0.45*100" in a value (45).
Another example, if I have two variables totalCost and contractVolume, and I have the string "totalCost * 1000 / contractVolume": how can I transform the string in the resulting value?
ex.
var totalCost = 10
var contractVolume = 100
var stringToCompute = "totalCost * 1000 / contractVolume"
console.log(compute(stringToCompute)) // -> 100
Obs:
I see a similar question, but in php, in the example he uses the method eval()
Url

you can also use eval() function in javascript
like --
eval("x + 17")

You can use eval() in JS too. Usually it is not a good idea if it is not mandatory, but it works.

Related

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.

transforming math expression from text into calculated one

inside certain calculation I'm generating an math expression in javascript like
var myExpression = '';
if (!isNaN(myVal) && myVal> 0) {
myExpression += '(' + myVal+ ' * ' + someVal + ') +';
}
and based on certain user events I'm getting generated expression in console.log as you expect
(1 * 1) + (10 * 5) + ...
or
(10 * 5) + ...
How can I transform this math expression representation into real expression and to store it's result into variable?
You can use eval() on the string, which will run it as JavaScript. This will allow the math expression to be computed:
eval(myExpression);
Just note be wary of using eval(). See Why is using the JavaScript eval function a bad idea. Although that being said there are many things people can now do with the JavaScript built-in console, as users can execute any JavaScript they wish on any web page. See the third comment by of this answer byPrestaul on potential problems this can have. If you ensure that the variables cannot be directly manipulated by the user then your fine.
You can use math.js, which comes with it's own expression parser:
math.eval('(1 * 1) + (10 * 5)'); // 51
or provide variables in a scope and use them in the expression:
math.eval('(myVal * someVal)', {myVal: 2, someVal: 10}); // 20
you can also parse an expression into a tree and do operations on the tree, see docs:
http://mathjs.org/docs/expressions/parsing.html
http://mathjs.org/docs/expressions/expression_trees.html

Combining retrieved values with javascript and jquery [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I Convert a String into an Integer in JavaScript?
I have a select element that contains options for products. What I want to achieve is when they pick an option the price on the page automatically adjusts. I have figured out how to retrieve those values but when I combine them it just puts two numbers together instead of actually adding them.
For example instead of outputting 60 when I have 50 + 10 it outputs 5010.
My code:
$('.product_options').change(function(){
var base_price = $('#base_price').html();
var add_price = $(this).find("option:selected").data('price');
var new_price = base_price+add_price;
console.log(new_price);
$('.current_price').html(base_price+add_price);
});
Is there a way I can convert them both to integers so the operation actually goes through?
Thanks in advance!
Use parseInt
$('.product_options').change(function(){
var base_price = parseInt($('#base_price').html(), 10); // 10 as second argument will make sure that base is 10.
var add_price = parseInt($(this).find("option:selected").data('price'), 10);
var new_price = base_price+add_price;
console.log(new_price);
$('.current_price').html(base_price+add_price);
});
Try:
var base_price = +$('#base_price').html();
var add_price = +$(this).find("option:selected").data('price');
See the mighty: Mozilla's Arithmetic Operators Reference - Unary Negation
Any values you pull out of the DOM are going to be strings, and need converting into number types before you can do mathematical operations with them.
parseInt( ... ) is a built in javascript function that converts a string into an integer, if the string consists of digits only.
If you need a decimal number, you can use parseFlaot.
var new_price = parseInt(base_price)+parseInt(add_price);
// new_price is now set to the sum of `base_price` and `add_price`
Use parseFloat or parseInt
$('.product_options').change(function(){
var base_price = $('#base_price').html();
var add_price = $(this).find("option:selected").data('price');
var new_price = parseFloat(base_price) + parseFloat(add_price);
console.log(new_price);
$('.current_price').html(base_price+add_price);
});
Yes there is.
intval = parseInt(string)
is what you're looking for.

javascript problem with implicitly typed variables

Forgive this novice question (novice in Javascript!).
In a html page I have a set of images with a name and a number: img1 img2 img3... img12...
And there is a JS function where I need to iterate from (say) img5 to last img.
If I write this:
function iterateImg(objImgID) {var imgNum = objImgID.replace("img","");
for (i=imgNum+1;i<20;i++)
.../...
The variable "i" is treated as a string, and i+1 receive the value "51" if the passed object's ID is img5.
Of course I can still iterate from 1 to n and only perform the desired task when the value of i reaches 6, but that would be an ugly fix.
How can I fix this please? How can I create a variable that will be treated as an integer before I use it as seed?
Besides, what would you recommend as best practice?
var imgNum = Number(objImgID.replace("img",""));
That'll do it.
Or better yet (because I love regex)
var imgNum = Number(objImgID.match(/[0-9]+/));
Use parseInt to convert the string to a number
var imgNum = parseInt(objImgID.replace("img", ""));
There are several ways to force JavaScript to convert it into a number
parseInt(x, 10) - the 10 is the base of the number
x - 0 - subtracting only works for numbers
x * 1 - multiplying also
var imgNum = parseInt(objImgID.replace("img",""), 10);
Now when you do var i=imgNum+1, it will perform addition of 2 integers.

Javascript format a number asin C#

I have a number which currently is 1,657,108,700 and growing. However I wish for it to show as
1,657,108k
Does javascript or html have a build in function to do this?
The value is being set throu javascript to a span field in html.
[edit]
From the comment I got my method as far as:
var start = '1,657,108,700';
start = (start / 1000).toFixed(0);
var finish = '';
while (start.length > 3)
{
finish = ','.concat(start.substring(start.length - 3, 3), finish);
start = start.substring(0, start.length - 3);
};
finish = start + finish + "k";
return finish;
however this returns 1,65,7k instead of 1,657,108k.. anyone know why?
var formattedNumber = Math.round(yourNumber / 1000).toLocaleString() + "k";
Turn the above into a function or not as appropriate. I'm not aware of a single function to do this, or of a way to cater for non-English versions of "k" (assuming there are some), but at least toLocaleString() should take care of the comma versus fullstop for thousands issue.
UPDATE: I posted the above without testing it; when I tried it out I found toLocaleString() formatted 1234 as 1,234.00. I had thought of fixing it by using a regex replace to remove trailing zeros except of course I can't be sure what character toLocaleString() is going to use for the decimal point, so that won't work. I guess you could write some code that uses toLocaleString() on a "control" number (e.g., 1.1) to see at runtime what character it uses for the decimal.
UPDATE 2 for your updated question, inserting the commas manually, I did it like this:
var unformattedNumber = 123456;
var a = unformattedNumber.toString().split("");
for (var i=a.length-3; i >0; i-=3)
a.splice(i,0,",");
var formattedNumber = a.join("") + "k";

Categories