JS Vars - Adding - javascript

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 :)

Related

Is parseInt doesn't needed for '*' in JavaScript? [duplicate]

This question already has answers here:
What exactly is Type Coercion in Javascript?
(9 answers)
Closed 2 years ago.
I have array, by which at some point am mapping the array and calculating sum and percentages. So while implementing the logic i saw that, when i use '*' directly its working but when i use '+' it just adds the two string
For example:
const a = '100';
const b = '10';
const c = a * b;
const d = a + b;
console.log(d)
When i checked the d , it gives '10010' and when c it gives '1000' ! How is this ?
But when i use parseInt(a) + parseInt(b) it works perfectly with 110 as output
In JavaScript there are no primitive datatypes like int, float etc. There are only variables which can be initialized with everything you need. For your example
const a = 100;
const b = 10;
const c = a * b;
const d = a + b;
console.log(d);
should work perfectly, because I removed ''. With '' the constant thinks it is a string provided. Without '' there are just the numbers saved in the constants. Also + doesn't work in your example, because as I said the constants think the numbers are a string due to ''. So it just puts this two "strings" together and not summing them up.

Javascript Unwanted Data Type Switching

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.

JQuery Calculation drops cents

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);
}

JavaScript typecasting issue while addition

When I use prompt() method in JavaScript as follows:
var n=prompt("Enter an integer"); //passing 2 as value
n=(n+n);
document.writeln("n+n value is:"+n);
Then (n+n) gets concatenated as 22 instead of addition as 4
But when I don't use prompt() ie.:
var n=2;
n=(n+n)
document.writeln("n+n value is:"+n);
then it works fine for addition and answer is 4
Why is it so?
prompt("Enter an integer"); returns string
convert it after, you can use parseInt()
var n = parseInt(prompt("Enter an integer"));
SEE FIDDLE DEMO
Use parseInt to convert String to Int
var n = parseInt( prompt("Enter an integer") ); //passing 2 as value
n=(n+n);
document.writeln("n+n value is:"+n);
More info here
A variable declared with datatype var can hold any type of variable which is assigned to it at a moment of time.
eg.
var j = 1; // here j will be an integer datatype and will act as int after this
var j = "1"; //here j will be a string datatype and will act as int after this
in your first case
var n=prompt("Enter an integer");
here a string will be saved in variable 'n'. hence n will act as a string variable. Therefore (n+n) will result in concatenation of two strings.
In your second case
var n = 2;
In here n is holding an integer therefore n acts as int variable.
Thats why (n+n) results into a SUM instead of concatenation.
Change
var n =prompt("Enter an integer")
to
var n = Number( prompt("Enter an integer") )
As if you do console.log(typeof n) you will get a string which means n is actually a string.
So concatenation of
n = '2' + '2';
is '22'
Hence you need to change it to a number. For this you can use Number() or parseInt().

how to read value zero using parseInt function

var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
var resstr=result.toString();
var res=resstr.split(".");
var test=parseInt(res[1].charAt(0));
var test1=parseInt(res[1].charAt(1));
this is my code when my value in res variable is 5.90 then I alert test & test1 variable
in test alert it shows correct value i.e. "9" but in test1 alert it shows message like "Nan"
if res variable contain value 5.35 then it work correct i.e.test=3 & test1=5
only it does not work when test1 contains value "0" it gives message "Nan"
The problem is that you create a string such as '12.3', and split it to 3. .charAt(1) on that string returns an empty string, '', which parseInt turns into a NaN.
Well, an easy and hacky fix would be:
test1 = test1 || 0;
You may also consider a calculation instead of string manipulation:
var result = 98.1234;
var d1 = Math.floor(result * 10) % 10;
var d2 = Math.floor(result * 100) % 10;

Categories