If I have a variable that is given a "numeric" value from a PHP echo...
var names_each = <?php echo $ind_name_each; ?>;
...and $ind_name_each is derived from a MySQL column of type decimal(5,2),
is it a number or a string in JavaScript?
if all_total = 6.00
and names_each = 5.00
and I do this:
all_total = parseInt(names_each) + all_total;
I get 56.00
all_total = names_each + all_total;
I get 5.006.00
all_total = parseFloat(names_each) + all_total;
I get 56.00
I need some understanding here.
Convert all_total from string to int / float too...
Because now, + in all three examples is string concatenation.
Both variables are strings:
var names_each = '5.0', all_total = '6.0';
so the + operation concatenates those strings:
console.log(names_each + all_total); // '5.0' + '6.0' => '5.06.0'
console.log(parseInt(names_each) + all_total); // 5 + '6.0' => '5' + '6.0' => '56.0'
but if you parse them to numbers first, then you can use + to add them:
all_total = parseInt(names_each) + parseInt(all_total);
console.log(all_total); // 5 + 6 => 11
In JavaScript, if either side of the + operator is a string value then both sides are converted to a string and the result of the operator is the string concatenation of those values. Here are some examples:
1 + 2 // 3
"1" + "2" // "12"
"1" + 2 // "12"
1 + "2" // "12"
Note that the last 3 cases have the same result.
Happy coding.
On your examples it's not clear where all_total comes from in the first place, but it must be a string, since you are getting string concatenation instead of addition.
To answer your first question, names_each is not a string, it's a number.
The output of this PHP file
var names_each = <?php echo $ind_name_each; ?>;
Should be something like this:
var names_each = 5;
or
var names_each = 5.1;
So, it's not a string, but an actual number in js. If the other side of your attempted addition is a string, you get string concatenation.
Your variables are strings, not numbers.
Therefore, unless you explicitly convert them to numbers, you get string concatenation.
The following will tell you what they are:
console.log(typeof names_each);
console.log(typeof all_total);
Here are some examples:
typeof "6.00" // The result is "string"
typeof 6.00 // The result is "number"
If you add some logging to your application, you should be able to see where it is turning into a string.
Also, you should know that the following occurs:
5.00 == "5.00" // The result is "true"
5.00 === "5.00" // The result is "false"
Using the triple equals prevents the JavaScript engine from implicitly casting the type of your variable. So, with === you will get a strict comparison with no auto-type casting.
Related
I am looking at the typeof a where var a = 2 + []. I expected the answer to be 2 of type number but I am getting '2' of type string. However, when I evaluate var b = 2 - [], I get the value to be 2 of type number. Can somebody assist me to understand this behavior.
const arr = [];
const a = 2 + arr;
console.log(a); // '2'
console.log(typeof a) // string
const b = 2 - arr;
console.log(b) // 2
console.log(typeof b); // number
//I expected the value a to be 2 of type
//number just as b
//If I toggle the boolean value of arr,
//both a and b evaluates to 2 of
//type number
+ with two operands is the "addition operator," which may do mathematical addition or string addition (concatenation) depending on its operands.
When any operand to + is an object, the JavaScript engine converts the object to a primitive. In your case, the array is an object. Converting an array to a primitive yields a string (as though you'd called their toString method, which basically does .join()). So then the + operator is dealing with a number and a string. When either operand is a string, + converts the other operand to string, and so you get "2" as the result. That is:
2 + [] becomes
2 + "" which becomes
"2" + "" which is
"2"
- with two operands is the "subtraction operator" and it's very different. It's only for math, it doesn't have any string meaning. That means it converts its arguments to numbers. Converting an array to number involves first converting it to a string, then converting the string to a number. [] becomes "" which converts to 0. So:
2 - [] becomes
2 - "" which becomes
2 - 0 which is
2
I'm attempting to update a value in an object and set it to the current value + another number. So for instance, if an object's value is 5, I want it to update like this: object key : current value (5) + 7
container[response["id"]]["quantity"] += quantity;
console.log(container[response["id"]].attr("quantity"));
This is what I'm currently attempting.. I end up with 57 instead of 12.
Any ideas?
You get as a string and + with strings concatenate them. First parse to the number using parseInt() or parseFloat() than add.
let number = parseInt(container[response["id"]]["quantity"]);
number += quantity;
container[response["id"]]["quantity"] = number;
The issue is, the value return by response["id"]]["quantity"] is a string. And when you try to add a number using + to a string, then it will concatenate it, something like 5 + 7 is 57. To deal with this, you have to parse the number to Int or to Float by using parseInt() or parseFloat(). Ex:
let num = parseInt(container[response["id"]]["quantity"]);
num += quantity;
container[response["id"]]["quantity"] = num;
Here's an easy one for you true believers: You can use + to convert a string to a number,
var thing = "12"
alert(thing);
alert(typeof thing); // string
thing = +thing;
alert(typeof thing); // number
if (thing == 112) alert("!"); // number
Can someone explain:
What is the name of this process?
How does + convert a string to a number?
Javascript uses a dynamic type system. For me it's a 'cast' operation.
The operator + could be a String operator ('a' + 'b') or an Number operator (1+2). It could be used also between Strings and numbers (remembering that 0 + '12' = 12 and '0'+'12' = '012')
By default, i think that the JS interpreter considered +thing as 0 + things so it casts this variable to a number
While I do know that the following question is stupid simple, it is related to a specific situation that I have been unable to find through Google. The following code is in Javascript.
Suppose there is a variable
x = x + 1;
I can see from a tutorial that this is supposed to work. However, how are we supposed to use this variable in a calculation?
I have tried with the following codes
var name = name + 1;
alert(name);
The above outputs "NaN"; whatever that is...
var name = name + 1;
name = 2;
alert(name);
The above outputs 2 which is simply overriding the original variable.
name = prompt("input any number");
var name = name + 1
alert(name);
The above outputs the input provided + 1 as a string, i.e. 01 where the input is "0" without quotes.
I remember from a ruby lesson that we use .to_i in order to convert a string to an integer. How do we go about doing this in Javascript?
var name = name + 1;
The above code declares a new variable called name which contains whatever name contained before, plus 1. Since name only just came into existence, it doesn't have a numeric value ("Not A Number", or NaN). Adding 1 to NaN gives NaN.
+ means different things in different contexts. If the two operands are numbers, then it does addition. If one operand is a String, it does String concatenation, so
var x = "2"; // x is the String "2"
alert(x+2); // "22"
var x = 2; // x is the number 2
alert(x+2); // 4
If you want to convert a String to a number, you can do
if (x) x = parseInt(x, 10);
where the second argument is the radix (i.e. the base of the number system), and you should use it. If someone entered 02 for example, the radix prevents javascript from treating that as an octal (or other) number.
Of course, you always need to make sure your variables are defined before you use them. I bet your NaN result is coming from the variable not being defined.
Your issue is that you never initialize name. For example:
var name = 0;
alert(name); // Name is 0
name = name + 1;
alert(name); // Name is 1
If you don't initialize it, it will give you NaN: Not a Number.
To turn a string into a number, use parseInt or parseFloat:
var name = prompt("input any number"); // I input 3
name = parseFloat(name);
name = name + 1;
alert(name); // Name is 4
Use parseInt to convert a string to a number.
The line x = x + 1 says "take the existing value of x, add one to it, and store the resulting value back in x again".
The line var name = name + 1 is meaningless since name does not have an existing value when the statement is executed. It is the same as saying undefined + 1 which is NaN (Not a Number).
Here are some examples of how the + operator works in JavaScript:
1 + 2 // number + number is a number -> 3
"1" + 2 // string + anything is a string => "12"
1 + "2" // anything + string is a string => "12"
"1" + "2" // string + string is a string => "12"
NaN means "not a number". Since name has no value when it is first declared, saying "var name = name + 1" doesn't have a numerical meaning, since name is in the process of being declared when used for the first time.
In the second example, name is determined to be a string. Javascript isn't as sensitive to types as some other languages, so it uses + as a concatenation operator instead of a numerical one, since it makes more sense in context,
This is all in the context of a larger program, so Im going to try keep it simple, showing the offending lines only. I have an array of values that are numbers in string form a la "84", "32", etc.
Yet THIS line
console.log(unsolved.length + " " + unsolved[0] + " " + parseInt(unsolved[0]) + " " + parseInt("84"));
prints:
4 "84" NaN 84
"84" is the array element Im trying to parseInt! Yet it won't work unless I take it out of the context of an array and have it explicitly written. What's going on?
You can try removing the quotations from the string to be processed using this function:
function stripAlphaChars(source) {
var out = source.replace(/[^0-9]/g, '');
return out;
}
Also you should explicitly specify that you want to parse a base 10 number:
parseInt(unsolved[0], 10);
parseInt would take everything from the start of its argument that looks like a number, and disregard the rest. In your case, the argument you're calling it with starts with ", so nothing looks like a number, and it tries to cast an empty string, which is really not a number.
You should make sure that the array element is indeed a string which is possible to parse to a number. Your array element doesn't contain the value '84', but actually the value '"84"' (a string containing a number encapsulated by ")
You'll want to remove the " from your array elements, possible like this:
function removeQuotationMarks(string) {
return (typeof string === 'string') ? string.replace(/"|'/g, '') : string;
}
unsolved = unsolved.map(removeQuotationMarks);
Now all the array elements should be ready to be parsed with parseInt(unsolved[x], 10)
First we need to replace " to ' in give data using Regex and replace and then we need to cast.
var i = 1;
var j = "22"
function stringToNumber(n) {
return (typeof n === 'string') ? parseInt(Number(n.replace(/"|'/g, ''))) : n;
}
console.log(stringToNumber(i)); // 1
console.log(stringToNumber(j)); // 22