This question already has answers here:
Using JavaScript's parseInt at end of string
(6 answers)
Closed 9 years ago.
JavaScript parseInt() does not seem to work the same way as Java parseInt().
A very simple example is:
document.write(parseInt(" 60 ") + "<br>"); //returns 60
document.write(parseInt("40 years") + "<br>"); //returns 40
document.write(parseInt("He was 40") + "<br>"); //returns NaN
Line 1 is ok. but I expect line 2 to give an error, since you can't actually convert 'years' to an integer. I believe JavaScript parseInt() just checks if the first few characters in a String are an Integer.
So how can I check that as long as there are non-Integers in the String, it will return NaN?
parseInt is designed for some flexibility in parsing integers. The Number constructor is less flexible with extra characters, but will also parse non-integers (thanks Alex):
console.log(Number(" 60 ")); // 60
console.log(Number("40 years")); // Nan
console.log(Number("He was 40")); // NaN
console.log(Number("1.24")); // 1.24
Alternatively, use a regular expression.
" 60 ".match(/^[0-9 ]+$/); // [" 60 "]
" 60 or whatever".match(/^[0-9 ]+$/); // null
"1.24".match(/^[0-9 ]+$/); // null
To check if string contains non-integers, use regex:
function(myString) {
if (myString.match(/^\d+$/) === null) { // null if non-digits in string
return NaN
} else {
return parseInt(myString.match(/^\d+$/))
}
}
I would use a regex, maybe something like the following.
function parseIntStrict(stringValue) {
if ( /^[\d\s]+$/.test(stringValue) ) // allows for digits or whitespace
{
return parseInt(stringValue);
}
else
{
return NaN;
}
}
The simplest way is probably using the unary plus operator:
var n = +str;
This will also parse floating point values though.
Below is an isInteger function that can be added to all String objects:
// If the isInteger function isn't already defined
if (typeof String.prototype.isInteger == 'undefined') {
// Returns false if any non-numeric characters (other than leading
// or trailing whitespace, and a leading plus or minus sign) are found.
//
String.prototype.isInteger = function() {
return !(this.replace(/^\s+|\s+$/g, '').replace(/^[-+]/, '').match(/\D/ ));
}
}
'60'.isInteger() // true
'-60'.isInteger() // true (leading minus sign is okay)
'+60'.isInteger() // true (leading plus sign is okay)
' 60 '.isInteger() // true (whitespace at beginning or end is okay)
'a60'.isInteger() // false (has alphabetic characters)
'60a'.isInteger() // false (has alphabetic characters)
'6.0'.isInteger() // false (has a decimal point)
' 60 40 '.isInteger() // false (whitespace in the middle is not okay)
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 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.
So to check if a string is a positive integer, I have done some research and found this solution here by someone:
Validate that a string is a positive integer
function isNormalInteger(str) {
return /^\+?(0|[1-9]\d*)$/.test(str);
}
However, I put this into test, and found that numbers with pure 0's on the decimal places does not seem to be working. For example:
15 ===> Works!
15.0 ====> Does not work :(
15.000 ===> Does not work :(
Build upon the existing method, how could I allow pure-0's on the decimal places and make them all work? Please note 15.38 should not work, but 15.00 should.
No need to use regex here.
function isNormalInteger(str) {
var n = parseInt(str);
return n > 0 && n == +str;
}
Then test it:
isNormalInteger(15)
true
isNormalInteger(15.00)
true
isNormalInteger(15.38)
false
isNormalInteger(-15)
false
isNormalInteger(-15.1)
false
First of all the function should be called isNormalNumber instead of isNormalInteger as it accepts decimals, then this is the REgex you need:
function isNormalNumber(str) {
return /^\+*[0-9]\d*(\.0+)?$/.test(str);
}
alert(isNormalNumber("+10.0") + "::" + isNormalNumber("+10.9") + "::" + isNormalNumber("10"));
Returns true::false:true.
EDIT:
This is an edit to avoid matching leading zeros like in the numbers 001234 and 07878:
^\+*[1-9]\d*(\.0+)?$|^0(\.0+)?$
Quick and dirty
function isNormalInteger(str) {
var ival=parseInt(str);
return ival!=NaN && ival>=0 && ival==parseFloat(str);
}
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
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to print number with commas as thousands separators in Javascript
I have a function that will add thousand seperators to a number, however it is not working well when a decimal is passed in:
function thousandSep(val) {
return String(val).split("").reverse().join("")
.replace(/(.{3}\B)/g, "$1,")
.split("").reverse().join("");
}
If I pass in 10000, I get 10,000 as expected.
However, passing in 10,000.00 I get 1,000,0.00.
How can I modify the function to handle decimals?
Don't use ., use \d
function thousandSep(val) {
return String(val).split("").reverse().join("")
.replace(/(\d{3}\B)/g, "$1,")
.split("").reverse().join("");
}
function format(n, sep, decimals) {
sep = sep || "."; // Default to period as decimal separator
decimals = decimals || 2; // Default to 2 decimals
return n.toLocaleString().split(sep)[0]
+ sep
+ n.toFixed(decimals).split(sep)[1];
}
format(4567354.677623); // 4,567,354.68