I have set a number variable under c. After running it through local storage and a couple functions, the variable has turned into a string. Instead of x adding to c , x adds a digit to c. Can anyone see the problem?
function hi() {
c += x;
document.getElementById("paragraph").textContent = "This is a string" + c;
localStorage.clocal = c;
}
function resetvar() {
c = localStorage.clocal;
}
function bla() {
if (localStorage.getItem("clocal") === "null") {
document.getElementById("parargraph").textContent = "This Works Okay";
} else {
document.getElementById("parargraph").textContent = "This is a string" + localStorage.credits;
}
}
the data put in localStorage always as string.
If you wanna to get as number that you have to parse it
like this
c = parseInt(localStorage.clocal);
That's the nature of JS. You can use parseInt(c, 10) + x or x + 1 * c to over come this.
It's a little bit difficult to follow the flow of these methods, but one glaring issue I see is this line:
c += x
In this situation, you're saying that you want to set c equal to the result of c + x where x is a string, instead of setting x equal to x + c? By making this assignment, you are converting c to a string. Then after that point is doesn't matter what else you do -- it will still be a string unless you re-assign it explicitly as an integer.
I hope I understand your intention correctly.. It is a bit unclear.
Related
I want to find a value of a numerical variable such that it makes the equation true. Example:
var a = random number;
var b = random number;
function (find var c such that a = b + c;) {
console.log(c);
}
Is it possible to make the computer search for the answer of c? and not such that you undo the equation where c = a - b, but such that as it checks answers it gets closer to the value of c.
I would do z-z, and then that's your number. But that's probably not what you are asking.
I was asked this question in an assessment I took and was not able to figure it out. Would like to know possible solutions.
Question:
Write one Javascript statement on the indicated line that will make the printed number always be between 10 and 20.
let x = 2;
let y = 8;
const a = function(b) {
return function(c) {
return x + y + Math.abs(b) + c;
};
};
// Statement will go here
const fn = a(x);
x = 4;
console.log(fn(Math.random() * 10));
I've tried assigning different values to variable y. But I think the culprit is to know what variable c would be in the nested function. Note that c would always be a number between 0 and 10 (as Math.random() is between 0 and 1, then multiplied by 10).
You already concluded correctly that the argument passed to fn is a random number between 0 and 10, which is c in the expression that the call to fn will evaluate: x + y + Math.abs(b) + c
So if fn must return a number between 10 and 20, then x + y + Math.abs(b) must equal 10.
We also see that the global variable x is set to 4 at a time that we cannot change it any more, but still before the call to fn, so that means y + Math.abs(b) must equal 6.
Now this gives us already a hint: as it stands, y is 8, which makes the conclusion in the previous paragraph impossible. So we must alter y. It is not yet too late, since the value of y will only be read when fn is called.
So what is Math.abs(b)? The local variable b is set when a is called. a is called with x, which at the time of that call is still 2. So Math.abs(b) is 2, and so we can derive that y must be 4.
One obvious way to make y to be 4 in one line:
y = 4;
(Alternatively, y-=4, y>>=1, y/=2, y^=12, ...etc)
If you want to provide a creative answer, try:
Math.random = function() { return 1.345; };
I have this block, that pulls the current amount paid on the item from Firebase and the amount being paid at the moment. Then it is supposed to add the two together to make the third variable.
For some reason the code drops the cents off the total.
singleRef.once("value", function(snapshot) {
var a = parseInt(snapshot.val().amounts.paid); // The amount already paid
var b = parseInt(invoice.payment.amount); // The amount being applied
var c = a + b;
console.log(c);
});
Let's say the following is happening:
a = 0;
b = 10.86;
The result in this code will be:
c = 10; // should be 10.86
Let's say the following is happening:
a = 10.00;
b = 10.86;
The result in this code will be:
c = 20; // should be 20.86
It doesn't matter what the cents are, it always rounds to get rid of them. I've tried adding .toFixed('2') to all of the variables, just a and b, and just c. All result in the same no cent totals.
HOW!? I've been trying to do this for the past few hours, it's probably simple but I can't figure it out. It's driving me nuts! I'm using angularjs and firebase.
The function parseInt() is specifically for parsing integers so, if you give it 3.14159, it will give you back 3.
If you want to parse a floating point value, try parseFloat().
For example, the following code:
var a = parseInt("3.141592653589");
var b = parseInt("2.718281828459");
var c = a + b;
alert(c);
var d = parseFloat("3.141592653589");
var e = parseFloat("2.718281828459");
var f = d + e;
alert(f);
will give you two different outputs:
5
5.859874482047999
As others have mentioned, you can't parse dollars and cents with parseInt().
And using floats is a bad idea for anything financial/monetary.
Most financial systems simply store prices/dollar values in cents, you can write a function to format it nicely for users if there is a need to display the values.
function(cents) {
cents = +cents; // unary plus converts cents into a string
return "$" + cents.substring(0, cents.length - 2) + "." + cents.substring(cents.length - 2);
}
You'll have to forgive me, I'm new to JavaScript...like a few weeks new. Anyway, I created a code using JavaScript to generate two random numbers, ask to add them, and give a "That is correct/that is incorrect" answer based on the users response. I wanted to add the other signs (-,*,/) to the equation and decided to try my hand at arrays to do so. Here is what I have so far:
<head>
<meta charset="utf-8" />
<title>Math Games</title>
</head>
<body>
<script>
var Answer;
var numbers=new Array();
var signs=new Array();
var Signs2=new Array();
var SignNoQuote=new Array();
numbers[0]=(Math.floor(Math.random() * 10 + 1));
numbers[1]=(Math.floor(Math.random() * 10 + 1));
signs[0]="+";
signs[1]="-";
signs[2]="*";
signs[3]="/";
SignNoQuote[0]="+";
SignNoQuote[1]="-";
SignNoQuote[2]="*";
SignNoQuote[3]="/";
Signs2[0]=(Math.floor(Math.random() * 4));
Answer=window.prompt("What is " + numbers[0] + signs[Signs2[0]] + numbers[1] + "?");
if(Answer==numbers[0] + SignNoQuote[Signs2[0]] + numbers[1])
{
window.alert("That's Correct!");
}
else
{
window.alert("That is Incorrect");
}
</script>
Refresh
</body>
It asks the question correctly, but when the right answer is given, it says that it is incorrect. I tried removing the quotation marks from the values of the "SignNoQuote" array hoping it would work, but when it is run that way, none of the script will run and the debugger claims it to be a syntax error? What am I doing wrong and how can I fix it?
If you want something specific to the use case you have, this will work nicely:
//A mapping from the symbol for an operation to
//the function that executes it.
var opFunction = {
"+": function (x, y) { return x + y; },
"-": function (x, y) { return x - y; },
"*": function (x, y) { return x * y; },
"/": function (x, y) { return x / y; }
};
//Gets the operation symbol.
var op = SignNoQuote[Signs2[0]];
//Looks up the function for the operation,
//then calls it with your numbers as operands.
var result = opFunction[op](numbers[0], numbers[1]);
However, if you need something general purpose for evaluating mathematical expressions, Brad's answer provides what you need.
If I'm understanding the problem, you are trying to use a string of a symbol to do math.
numbers[0] + SignNoQuote[Signs2[0]] + numbers[1]
The trouble with this is that + means concatenation when used in the context of strings. You don't have a + operator in code, you have the string of text with one character, +. These are fundamentally different. It's no different than this:
numbers[0] + '+' + numbers[1]
.... which results in something like this:
"1+2"
What you need to do is actually execute that input somehow, such as with eval(). Unfortunately, this is where you run into some scary security issues, allowing users to execute whatever they want. In some contexts this can be safe, but usually it isn't.
There are options for you to run this equation. See this question for details: Evaluating a string as a mathematical expression in JavaScript
When you're checking you're answer, you use a comparison to:
numbers[0] + SignNoQuote[Signs2[0]] + numbers[1]
But assuming you want it to multiply, what that actually is, is something like:
2 + "*" + 1
Which is not the same as:
2 * 1
The easiest way to do this would probably be with a if ... else if ... else if ... statement. Something like:
var answerCorrect = false;
if (SignNoQuote[Signs2[0]] == "+") {
answerCorrect = (Answer == numbers[0] + numbers[1]);
} else if (SignNoQuote[Signs2[0]] == "*") {
answerCorrect = (Answer == numbers[0] * numbers[1]);
} else if (etc ...
then:
if(answerCorrect) {
window.alert("That's Correct!");
} else {
window.alert("That is Incorrect");
}
I have two variables, 'a' and 'b' in my JavaScript, and i want to add them together - i assume this code:
var a = 10;
var b = 30
var varible = a + b;
This, puts the two numbers next to each other... any ideas why... the result should be 40?
You probably have strings instead of integers. That is your code really is like this:
var a = "10";
var b = "30";
var c = a + b; // "1030"
There are several ways to convert the strings to integers:
a = parseInt(a, 10); // Parse the string
b = b * 1; // Force interpretation as number
new is a reserved word, I'd use something else in any case.
And with a normal variable name of c it worked for me:
var a = 10;
var b = 30
var c = a + b;
alert(c);
did the expected and alerted 40
new is a keyword in JavaScript. you should not use it to declare your variables or functions. change the variable name from new to something else
Are you sure you didn't do this:
var a = '30';
var b = '40';
Here, I show '30' as a string rather than a number, and I would expect the "+" operator to concatenate two strings. Since this is contrived code, you may not be entirely sure where your variables were initially assign or what type they have. You can check it like this:
var a = '30';
var b = '40';
alert( typeof(a) + '\n' + typeof(b) );
If either of those say 'object' or 'string' rather than 'number' this is your problem. One way this might happen that you didn't expect is with an input. Say you have code like this:
<input id="a" value="30" />
<input id="b" value="40" />
<script language="javascript">
var a = document.getElementById('a').value;
var b = document.getElementById('b').value;
</script>
Here, the value of a text input is always a string initially.
If you want to convert a variable to a number first you should use something like myVar - 0 to coerce a numeric operation or the more-formal parseInt() or parseFloat() functions (don't forget the radix parameter for parseInt()). And always check isNaN() on the results.
I'm really surprised that noone has until now suggested the obvious: "Casting" with JavaScript (I set it in quotes, because it is no real casting).
var a = "1"; // string
var b = Number(a); // number
var c = String (b); // string again
a + b; // "11"
b + a; // 2
a + c; // "11"
Now, why is this no real casting? Because you don't create a new variable of type "number" but a new object "Number" and initialize it with something that could be numerical.
One or both is a string. If you get the values from a HTML input or something, they definitely are. Make sure they're both integers by using parseInt:
var newValue = parseInt(a,10) + parseInt(b,10);
Also, 'new' is a keyword. You can't use that for a variable name :)