Add two values together in Mootools - javascript

My Javascript / Mootools knowledge is limited, so I am having trouble figuring out how to take the following code and make it produce a sum and assign the value to the ordertotal variable.
$('ordertotal').value = '$' + 100 * $('tickets').value + 10 * $('fiftytickets').value + '.00';
The tickets variable is either 1 or 2 depending on the user selection and the fiftytickets variable is either 0.5, 2.5 or 5.0 depending of the user selection. Both variables are supplied values using a HTML select menu and they function correctly when used individually.
For example:
$('ordertotal').value = '$' + 100 * $('tickets').value + '.00';
Works correctly and
$('ordertotal').value = '$' + 10 * $('fiftytickets').value + '.00';
Works correctly, but I can figure out how to add them together and assign them to the ordertotal variable.
Any assistance with this issue would be greatly appreciated.
Thank you.
Mike

Seems like you are trying to get sum of string + int + int + string
Your two examples worked, because there was only concatenation (string + int(converted to string) + string)
And when you add a nubmer to a "$" - your number get converted to a string. What you can do is to either put numbers sum in () or get the value separately:
sumValue = 100 * $('tickets').value + 10 * $('fiftytickets').value
$('ordertotal').value = '$' + sumValue + '.00';
Example:
> "1" + 1
"11"
> "$" + 1 + ".00"
"$1.00"
> "$" + 1 + 1 + ".00"
"$11.00"
> "$" + (1 + 1) + ".00"
"$2.00"

Related

How to save the function random number inside a variable [duplicate]

This question already has an answer here:
Javascript variable declared as code and reuse
(1 answer)
Closed 3 years ago.
I want to do something like this:
var randomNum = Math.floor(Math.random() * 10 + 1);
console.log("What is the answer of: " + randomNum + " + " + randomNum + "?");
console.log("What is the answer of: " + randomNum + " + " + randomNum + "?");
console.log("What is the answer of: " + randomNum + " + " + randomNum + "?");
console.log("What is the answer of: " + randomNum + " + " + randomNum + "?");
and inside the console I want it to get:
What is the answer of: 5 + 6?
when we refresh the page we should get another number for example:
What is the answer of: 3 + 1?
etc..
normal random function but with assigning it to a variable;
because when I do that it just keep printing the same number?
insde my console:
What is the answer of: 1 + 1?
second refresh
What is the answer of: 3 + 3?
third refresh:
What is the answer of: 2 + 2?
and so on, The both cells has the same value?
I can fix it without DRY (don't repeat your self) by the basic structure:
//var randomNum = Math.floor(Math.random() * 10 + 1);
console.log("What is the answer of: " + Math.floor(Math.random() * 10 + 1) + " + " + Math.floor(Math.random() * 10 + 1) + "?");
But as you know maybe I'm doing a big project so I should not repeat my self, right?
When you do it like this: var randomNum = Math.floor(Math.random() * 10 + 1);, first the right side of the expression is evaluated, then assigned into randomNum. So ofc it will stay the same.
just turn it into a function:
randomNum = () => Math.floor(Math.random() * 10 + 1);
This will work, you need to make it a function
var randomNum = () => Math.floor(Math.random() * 10 + 1);
then you can use it as randomNum()
You can simply create a function that creates 2 unique random numbers and call it upon DOMContentLoaded event being fired:
//Call your random number function when DOM is fully loaded and parsed
window.addEventListener('DOMContentLoaded', init)
function init() {
//We have to create 2 unique random numbers here (not just one):
const a = Math.floor(Math.random() * 10 + 1),
b = Math.floor(Math.random() * 10 + 1);
console.log(`${a} + ${b} = ${a + b}`);
}

why the odd results adding floats in javascript?

I have javascript code like this:
var strikePrice = parseFloat(this.props.data.strike).toFixed(1);
var commission = parseFloat(this.props.commission / 100).toFixed(2);
var callInMoney = parseFloat(strikePrice + this.state.callPrice + commission).toFixed(2);
var putInMoney = parseFloat(strikePrice - this.state.putPrice - commission).toFixed(2);
console.log("strikePrice: " + strikePrice + " commission: " + commission);
console.log("callprice: " + this.state.callPrice + " putprice: " + this.state.putPrice);
console.log("call: " + callInMoney + " put: " + putInMoney);
and the output is this:
strikePrice: 34.0 commission: 0.08
callprice: 0 putprice: 0
call: 34.00 put: 33.92
That is wrong. The call should be 34.08 (8 cents higher) just like the put is 8 cents lower.
Why is the results not correct?
Thank you
Matt
toFixed returns a string so you're actually doing some string concatenation rather than the arithmetic you expect.
Check out what happens when you just print out your initial addition.
var strikePrice = parseFloat('34').toFixed(1);
var commission = parseFloat('0.08').toFixed(2);
console.log(strikePrice + 0 + commission);
Instead, you'll need to convert those strings to numbers first.
var strikePrice = parseFloat('34').toFixed(1);
var commission = parseFloat('0.08').toFixed(2);
strikePrice = parseFloat(strikePrice);
commission = parseFloat(commission);
console.log(strikePrice + 0 + commission);
This expression:
strikePrice + this.state.callPrice + commission
Evaluates to this value:
"34.000.08"
Because commission is a string value, which is because [toFixed()][1] takes an integer and returns a string.
You need to refactor your code so that commission is a float value, or so that you call parseFloat() again on the parameters of line 3.
I can't comment on why putInMoney works for you. For me it gave "NaN".

Declaring variable within functions

Ok, so I I'm having this strange behaviour that I cannot explain. Look at the following:
$("#completeData").on("click", function() {
var toUpdate = {};
var toUpdateCount = 0;
var ratios = {};
This.calculateGradePerSize();
//1) Select all sizes that are equal to NA or are Equal to 0 (means its a new one)
$.each(This.logements, function(key, l) {
if (l.sizeMyId === "NA" || l.sizeMyId === 0) {
toUpdate[l.rueNum] = l;
toUpdateCount++;
} else { //else init the ratios because it means they are actually present
/**
//My problem is this variable,
I want it to be equal to an empty object
But for reasons I cannot seem to understand,
it takes in account the latter modification in the code
that happens to this variables
*/
ratios[l.sizeMyId] = {};
}
});
console.log(toUpdate);
console.log(ratios);
console.log(This.sizeRatio);
//2) Calculate Ratios and build the ratios function of the toUpdate
$.each(This.sizeRatio, function(sizeMyId, count) {
if (sizeMyId !== "NA" && sizeMyId != 0) {
console.log("COUNT SIZE: " + count + " COUNT LOGEMENT: " + This.countLogement + " toUpdateCount: " + toUpdateCount + " SizeMyId: " + sizeMyId);
console.log("Calculation: " + count / This.countLogement * toUpdateCount);
ratios[sizeMyId].count = Math.ceil(count / This.countLogement * toUpdateCount);
console.log("Calculation WITH CEIL: " + Math.ceil(count / This.countLogement * toUpdateCount));
ratios[sizeMyId].grade = This.sizeGrade[sizeMyId];
ratios[sizeMyId].sizeMyId = sizeMyId;
}
});
console.log(ratios);
});
As explained in the multiline comment, my problem is the ratio variable. I tried declaring the variable without var prefix, so that JS doesn't know its existence but still, I want it to be empty object. In fact, the problem has stronger roots than simply that, I cannot update it. Each change I make to the ratios var are not registered, but I wanna start with the beginning how can I make sure that this variable is empty at the beginning of the function.
I don't know if this question is really worth. Thinking about deleting it. My bug was that the count variable in the each function as well as the ratio definition were the same hence not registering.
As for the variable not being an empty one at function start. It simply how the JS engine works. If there is something not working, more likely than not, there is something wrong in your code.
$.each(This.sizeRatio, function (sizeMyId, count) {
if (sizeMyId !== "NA" && sizeMyId != 0) {
console.log("COUNT SIZE: " + count + " COUNT LOGEMENT: " + This.countLogement + " toUpdateCount: " + toUpdateCount + " SizeMyId: " + sizeMyId);
console.log("Calculation: " + count / This.countLogement * toUpdateCount);
//HERE ratios[sizeMyId].count IS THE SAME than the anonymous function.
ratios[sizeMyId].count = Math.ceil(count / This.countLogement * toUpdateCount);
console.log("Calculation WITH CEIL: " + Math.ceil(count / This.countLogement * toUpdateCount));
ratios[sizeMyId].grade = This.sizeGrade[sizeMyId];
ratios[sizeMyId].sizeMyId = sizeMyId;
}
});

Generate numeric id in a range between 1 to 10

I'm using a script that dynamically combines a category name with an item id. It will then call images from a folder that match the file name. It consists of the file path, category name and item id e.g. Banking-1.jpg, Banking-2.jpg, etc.
var f = {
image: "/img/" + this.item.Categories[0].Category + "-" + this.itemId + ".jpg"
}
Right now it just returns a value like Banking-50.jpg, for which there is no existing image. Is it possible to define a range so that the maximum value it can return is Banking-10.jpg?
You can cap the integer with the Math.min and Math.max functions. See the following example.
var f = {
image: "/img/" + this.item.Categories[0].Category + "-" + Math.min(Math.max(this.itemId, 0), 10) + ".jpg"
}
This will work unless this.itemId is a string, in which case you will need to cast it to an integer with parseInt.
var f = {
image: "/img/" + this.item.Categories[0].Category + "-" + Math.min(Math.max(parseInt(this.itemId,10), 0), 10) + ".jpg"
}
If you like, you can define a helper function like this.
function capToRange(i, min, max)
{
return Math.min(Math.max(i, min), max);
}
And use it like this.
var f = {
image: "/img/" + this.item.Categories[0].Category + "-" + capToRange(this.itemId, 0, 10) + ".jpg"
}

Why I got NaN in this javaScript code?

First I test that every variable got a number value:
09-11 18:15:00.420:
d_drop: -1.178791867393647
drop_at_zero: 0.0731037475605623
sightHeight: 4.5
d_distance: 40
zeroRange: 10
09-11 18:15:00.420:
d_drop: true
drop_at_zero: true
sightHeight: true
d_distance: true
zeroRange: true
function isNumber (o) {
return ! isNaN (o-0) && o != null;
}
var d_drop; // in calculation this gets value 1.1789
var d_path = -d_drop - sightHeight + (drop_at_zero + sightHeight) * d_distance / zeroRange;
console.log("Path: " + d_path + " cm");
and in the log:
09-11 18:15:00.430: D/CordovaLog(1533): Path: NaN cm
WHY? I have tried to figure that out couple of hours now and no success, maybe someone has an idea, I haven't!
Thanks!
Sami
-------ANSWER IS that parse every variable when using + operand-----------
var d_path = parseFloat(-d_drop) - parseFloat(sightHeight) + (parseFloat(drop_at_zero) + parseFloat(sightHeight)) * parseFloat(d_distance) / parseFloat(zeroRange);
The addition operator + will cast things as strings if either operand is a string. You need to parse ALL of your inputs (d_drop, sightHeight, etc) as numbers before working with them.
Here's a demo of how the + overload works. Notice how the subtraction operator - is not overloaded and will always cast the operands to numbers:
var numberA = 1;
var numberB = 2;
var stringA = '3';
var stringB = '4';
numberA + numberB // 3 (number)
numberA - numberB // -1 (number)
stringA + stringB // "34" (string)
stringA - stringB // -1 (number)
numberA + stringB // "14" (string)
numberA - stringB // -3 (number)
http://jsfiddle.net/jbabey/abwhd/
At least one of your numbers is a string. sightHeight is the most likely culprit, as it would concatenate with drop_at_zero to produce a "number" with two decimal points - such a "number" is not a number, hence NaN.
Solution: use parseFloat(varname) to convert to numbers.
If you're using -d_drop as a variable name, that is probably the culprit. Variables must start with a letter.
var d_drop = -1.178791867393647,
drop_at_zero = 0.0731037475605623,
sightHeight = 4.5,
d_distance = 40,
zeroRange = 10;
var d_path = d_drop - sightHeight + (drop_at_zero + sightHeight) * d_distance / zeroRange;
console.log("Path: " + d_path + " cm"); // outputs: Path: 12.613623122848603 cm

Categories

Resources