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
Related
I store some parameters client-side in HTML and then need to compare them as integers. Unfortunately I have come across a serious bug that I cannot explain. The bug seems to be that my JS reads parameters as strings rather than integers, causing my integer comparisons to fail.
I have generated a small example of the error, which I also can't explain. The following returns 'true' when run:
console.log("2" > "10")
Parse the string into an integer using parseInt:
javascript:alert(parseInt("2", 10)>parseInt("10", 10))
Checking that strings are integers is separate to comparing if one is greater or lesser than another. You should always compare number with number and string with string as the algorithm for dealing with mixed types not easy to remember.
'00100' < '1' // true
as they are both strings so only the first zero of '00100' is compared to '1' and because it's charCode is lower, it evaluates as lower.
However:
'00100' < 1 // false
as the RHS is a number, the LHS is converted to number before the comparision.
A simple integer check is:
function isInt(n) {
return /^[+-]?\d+$/.test(n);
}
It doesn't matter if n is a number or integer, it will be converted to a string before the test.
If you really care about performance, then:
var isInt = (function() {
var re = /^[+-]?\d+$/;
return function(n) {
return re.test(n);
}
}());
Noting that numbers like 1.0 will return false. If you want to count such numbers as integers too, then:
var isInt = (function() {
var re = /^[+-]?\d+$/;
var re2 = /\.0+$/;
return function(n) {
return re.test((''+ n).replace(re2,''));
}
}());
Once that test is passed, converting to number for comparison can use a number of methods. I don't like parseInt() because it will truncate floats to make them look like ints, so all the following will be "equal":
parseInt(2.9) == parseInt('002',10) == parseInt('2wewe')
and so on.
Once numbers are tested as integers, you can use the unary + operator to convert them to numbers in the comparision:
if (isInt(a) && isInt(b)) {
if (+a < +b) {
// a and b are integers and a is less than b
}
}
Other methods are:
Number(a); // liked by some because it's clear what is happening
a * 1 // Not really obvious but it works, I don't like it
Comparing Numbers to String Equivalents Without Using parseInt
console.log(Number('2') > Number('10'));
console.log( ('2'/1) > ('10'/1) );
var item = { id: 998 }, id = '998';
var isEqual = (item.id.toString() === id.toString());
isEqual;
use parseInt and compare like below:
javascript:alert(parseInt("2")>parseInt("10"))
Always remember when we compare two strings.
the comparison happens on chacracter basis.
so '2' > '12' is true because the comparison will happen as
'2' > '1' and in alphabetical way '2' is always greater than '1' as unicode.
SO it will comeout true.
I hope this helps.
You can use Number() function also since it converts the object argument to a number that represents the object's value.
Eg: javascript:alert( Number("2") > Number("10"))
+ operator will coerce the string to a number.
console.log( +"2" > +"10" )
The answer is simple. Just divide string by 1.
Examples:
"2" > "10" - true
but
"2"/1 > "10"/1 - false
Also you can check if string value really is number:
!isNaN("1"/1) - true (number)
!isNaN("1a"/1) - false (string)
!isNaN("01"/1) - true (number)
!isNaN(" 1"/1) - true (number)
!isNaN(" 1abc"/1) - false (string)
But
!isNaN(""/1) - true (but string)
Solution
number !== "" && !isNaN(number/1)
The alert() wants to display a string, so it will interpret "2">"10" as a string.
Use the following:
var greater = parseInt("2") > parseInt("10");
alert("Is greater than? " + greater);
var less = parseInt("2") < parseInt("10");
alert("Is less than? " + less);
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 was wondering what the = +_ operator means in JavaScript. It looks like it does assignments.
Example:
hexbin.radius = function(_) {
if (!arguments.length)
return r;
r = +_;
dx = r * 2 * Math.sin(Math.PI / 3);
dy = r * 1.5;
return hexbin;
};
r = +_;
+ tries to cast whatever _ is to a number.
_ is only a variable name (not an operator), it could be a, foo etc.
Example:
+"1"
cast "1" to pure number 1.
var _ = "1";
var r = +_;
r is now 1, not "1".
Moreover, according to the MDN page on Arithmetic Operators:
The unary plus operator precedes its operand and evaluates to its
operand but attempts to converts it into a number, if it isn't
already. [...] It can convert string representations of integers and
floats, as well as the non-string values true, false, and null.
Integers in both decimal and hexadecimal ("0x"-prefixed) formats are
supported. Negative numbers are supported (though not for hex). If it
cannot parse a particular value, it will evaluate to NaN.
It is also noted that
unary plus is the fastest and preferred way of converting something into a number
It is not an assignment operator.
_ is just a parameter passed to the function.
hexbin.radius = function(_) {
// ^ It is passed here
// ...
};
On the next line r = +_; + infront casts that variable (_) to a number or integer value and assigns it to variable r
DO NOT CONFUSE IT WITH += operator
=+ are actually two operators = is assignment and + and _ is variable name.
like:
i = + 5;
or
j = + i;
or
i = + _;
My following codes will help you to show use of =+ to convert a string into int.
example:
y = +'5'
x = y +5
alert(x);
outputs 10
use: So here y is int 5 because of =+
otherwise:
y = '5'
x = y +5
alert(x);
outputs 55
Where as _ is a variable.
_ = + '5'
x = _ + 5
alert(x)
outputs 10
Additionally,
It would be interesting to know you could also achieve same thing with ~ (if string is int string (float will be round of to int))
y = ~~'5' // notice used two time ~
x = y + 5
alert(x);
also outputs 10
~ is bitwise NOT : Inverts the bits of its operand. I did twice for no change in magnitude.
It's not =+. In JavaScript, + means change it into number.
+'32' returns 32.
+'a' returns NaN.
So you may use isNaN() to check if it can be changed into number.
It's a sneaky one.
The important thing to understand is that the underscore character here is actually a variable name, not an operator.
The plus sign in front of that is getting the positive numerical value of underscore -- ie effectively casting the underscore variable to be an int. You could achieve the same effect with parseInt(), but the plus sign casting is likely used here because it's more concise.
And that just leaves the equals sign as just a standard variable assignment.
It's probably not deliberately written to confuse, as an experienced Javascript programmer will generally recognise underscore as a variable. But if you don't know that it is definitely very confusing. I certainly wouldn't write it like that; I'm not a fan of short meaningless variable names at the best of times -- If you want short variable names in JS code to save space, use a minifier; don't write it with short variables to start with.
= +_ will cast _ into a number.
So
var _ = "1",
r = +_;
console.log(typeof r)
would output number.
I suppose you mean r = +_;? In that case, it's conversion of the parameter to a Number. Say _ is '12.3', then +'12.3' returns 12.3. So in the quoted statement +_ is assigned to r.
_ is just a a variable name, passed as a parameter of function hexbin.radius , and + cast it into number
Let me make a exmple same like your function .
var hexbin = {},r ;
hexbin.radius = function(_) {
if (!arguments.length)
return r;
console.log( _ , typeof _ )
r = +_;
console.log( r , typeof r , isNaN(r) );
}
and run this example function .. which outputs
hexbin.radius( "1");
1 string
1 number false
hexbin.radius( 1 );
1 number
1 number false
hexbin.radius( [] );
[] object
0 number false
hexbin.radius( 'a' );
a string
NaN number true
hexbin.radius( {} );
Object {} object
NaN number true
hexbin.radius( true );
true boolean
1 number false
It Will assign new value to left side variable a number.
var a=10;
var b="asg";
var c=+a;//return 10
var d=-a;//return -10
var f="10";
var e=+b;
var g=-f;
console.log(e);//NAN
console.log(g);//-10
Simply put, +_ is equivalent to using the Number() constructor.
In fact, it even works on dates:
var d = new Date('03/27/2014');
console.log(Number(d)) // returns 1395903600000
console.log(+d) // returns 1395903600000
DEMO:
http://jsfiddle.net/dirtyd77/GCLjd/
More information can also be found on MDN - Unary plus (+) section:
The unary plus operator precedes its operand and evaluates to its operand but attempts to converts it into a number, if it isn't already. Although unary negation (-) also can convert non-numbers, unary plus is the fastest and preferred way of converting something into a number, because it does not perform any other operations on the number. It can convert string representations of integers and floats, as well as the non-string values true, false, and null. Integers in both decimal and hexadecimal ("0x"-prefixed) formats are supported. Negative numbers are supported (though not for hex). If it cannot parse a particular value, it will evaluate to NaN.
+_ is almost equivalent of parseFloat(_) . Observe that parseInt will stop at non numeric character such as dot, whereas parshFloat will not.
EXP:
parseFloat(2.4) = 2.4
vs
parseInt(2.4) = 2
vs
+"2.4" = 2.4
Exp:
var _ = "3";
_ = +_;
console.log(_); // will show an integer 3
Very few differences:
Empty string "" evaluates to a 0, while parseInt() evaluates to NaN
For more info look here: parseInt vs unary plus - when to use which
In this expression:
r = +_;
'+' acts here as an unary operator that tries to convert the value of the right operand. It doesn't convert the operand but the evaluated value. So _ will stay "1" if it was so originally but the r will become pure number.
Consider these cases whether one wants to apply the + for numeric conversion
+"-0" // 0, not -0
+"1" //1
+"-1" // -1
+"" // 0, in JS "" is converted to 0
+null // 0, in JS null is converted to 0
+undefined // NaN
+"yack!" // NaN
+"NaN" //NaN
+"3.14" // 3.14
var _ = "1"; +_;_ // "1"
var _ = "1"; +_;!!_ //true
var _ = "0"; +_;!!_ //true
var _ = null; +_;!!_ //false
Though, it's the fastest numeric converter I'd hardly recommend one to overuse it if make use of at all. parseInt/parseFloat are good more readable alternatives.
This has become more of a pondering about how javascript works, than an actual problem to fix. In the case of a statement like
var str = 9 + " some words here";
The resultant str var would contain the value "9 some words here". My question is what function does javascript use to automatically coerce the Number object '9' into a string to be concatenated with the String object " some words here", and is this function changeable/overrideable.
This started from me needing to output single digits with a preceding 0 on a page. This was easy enough to accomplish with a quick prototype function on the Number object
Number.prototype.SpecialFormat = function() {
if(this < 10) {
return "0" + this;
}
else {
return this.toString();
}
};
And call it with a simple (9).SpecialFormat() + " words here";
But that got me wondering if I could overwrite the toString function on a Number with a
Number.prototype.toString = function() {
if(this < 10) {
return "0" + this;
}
else {
return this;
}
};
, and just let javascripts automatic conversion handle it for me, so I could use a standard 9 + " words here"; to get the same result "09 words here". This did not just implicitly work, I had to end up adding .toString to the 9 (9).toString() + " words here" (which upon taking a further look, would have resulted in some infinite loops).
So is there a way to override the built in functionality of a javascript native type ?
*Note: I realize this is likely a 'worst idea ever'
The addition operator coerces its arguments to strings in step 7:
If Type(lprim) is String or Type(rprim) is String, then
Return the String that is the result of concatenating ToString(lprim) followed by ToString(rprim)
The ToString operation has special rules for numbers, detailed under "ToString Applied to the Number Type".
It appears that the abstract operation ToString(number) does not ever use Number.prototype.toString. In fact, ti's the other way around: the default Number.prototype.toString function employs the abstract numeric ToString algorithm. Thus, it's not possible to override the default behavior for the stringification of numbers during type coercion in ECMAScript 5, because there's no way to alter the language-defined ToString operation.
ToString does use the target's toString method when coercing objects to strings, but not number primitive values.
(not strictly an answer but I need some space)
Be very careful with type coercion, especially when combining primitive types with their object counterparts because:
var n = 9;
typeof n; // "number"
n instanceof Number; // false!!
n = new Number(9);
n instanceof Number; // true, oh thank God
typeof n; // "object" what!!
Also, toString on Number doesn't actually work:
Number.prototype.toString = function () { return "foo" + this; };
var n = new Number(9);
"" + n; // "9", not "foo9"
A way to avoid this mess is by having:
var ns = {
number: {
specialFormat: function () /* .. */ }
}
}
ns.number.specialFormat(9); // "09"
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.