Which one of these to JS snippets are better in terms of style?
var answer = Number(prompt('What is the value of 2 + 2?'));
if (answer === 4) {
// do something
}
vs.
var answer = prompt('What is the value of 2 + 2?');
if (answer == 4) {
// do something
}
I'd say the first one is better because it is more explicit (and no type coercion will happen).
They are both wrong, because you should use parseInt(XX, 10) for this. And remember, every time you use == Jesus kills a puppy. So always use ===, and therefore: always check against the correct type.
It depends on what you want to do with answer. If the only thing you want to do is compare it, you don't need to convert the type:
var answer = prompt('What is the value of 2 + 2?');
if (answer === "4") {
// do something
}
If you want to end up with a number for comparison and then further processing, Number or the unary plus operator + will convert the output string to a numeric value, or NaN if it is not a valid base 10 number.
var answer = +prompt('What is the value of 2 + 2?');
if (answer === 4) {
// do something
}
There is a difference between parseInt(x, 10) and Number(x) - the former will ignore non-numeric characters at the end.
parseInt("4Hello World"); // 4
Number("4Hello World"); //NaN
+"4Hello World"; //NaN
Well of course the first one because, as you mentioned, no type coercion happens.but you should use parseInt:
var answer = parseInt((prompt('What is the value of 2 + 2?'), 10)) ;
Better would be
var n = prompt("What is the value of 2 + 2?");
n = parseInt(n, 10);
//and check
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);
This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 1 year ago.
I need javascript to add 5 to an integer variable, but instead it treats the variable as a string, so it write out the variable, then add 5 onto the end of the "string". How can I force it to do math instead?
var dots = document.getElementById("txt").value; // 5
function increase(){
dots = dots + 5;
}
Output: 55
How can I force it to output 10?
You have the line
dots = document.getElementById("txt").value;
in your file, this will set dots to be a string because the contents of txt is not restricted to a number.
to convert it to an int change the line to:
dots = parseInt(document.getElementById("txt").value, 10);
Note: The 10 here specifies decimal (base-10). Without this some browsers may not interpret the string correctly. See MDN: parseInt.
the simplest:
dots = dots*1+5;
the dots will be converted to number.
DON'T FORGET - Use parseFloat(); if your dealing with decimals.
I'm adding this answer because I don't see it here.
One way is to put a '+' character in front of the value
example:
var x = +'11.5' + +'3.5'
x === 15
I have found this to be the simplest way
In this case, the line:
dots = document.getElementById("txt").value;
could be changed to
dots = +(document.getElementById("txt").value);
to force it to a number
NOTE:
+'' === 0
+[] === 0
+[5] === 5
+['5'] === 5
parseInt() should do the trick
var number = "25";
var sum = parseInt(number, 10) + 10;
var pin = number + 10;
Gives you
sum == 35
pin == "2510"
http://www.w3schools.com/jsref/jsref_parseint.asp
Note: The 10 in parseInt(number, 10) specifies decimal (base-10). Without this some browsers may not interpret the string correctly. See MDN: parseInt.
This also works for you:
dots -= -5;
You can add + behind the variable and it will force it to be an integer
var dots = 5
function increase(){
dots = +dots + 5;
}
Number()
dots = document.getElementById("txt").value;
dots = Number(dots) + 5;
// from MDN
Number('123') // 123
Number('123') === 123 /// true
Number('12.3') // 12.3
Number('12.00') // 12
Number('123e-1') // 12.3
Number('') // 0
Number(null) // 0
Number('0x11') // 17
Number('0b11') // 3
Number('0o11') // 9
Number('foo') // NaN
Number('100a') // NaN
Number('-Infinity') //-Infinity
its really simple just
var total = (1 * yourFirstVariablehere) + (1 * yourSecondVariablehere)
this forces javascript to multiply because there is no confusion for * sign in javascript.
After trying most of the answers here without success for my particular case, I came up with this:
dots = -(-dots - 5);
The + signs are what confuse js, and this eliminates them entirely. Simple to implement, if potentially confusing to understand.
UPDATED since this was last downvoted....
I only saw the portion
var dots = 5
function increase(){
dots = dots+5;
}
before, but it was later shown to me that the txt box feeds the variable dots. Because of this, you will need to be sure to "cleanse" the input, to be sure it only has integers, and not malicious code.
One easy way to do this is to parse the textbox with an onkeyup() event to ensure it has numeric characters:
<input size="40" id="txt" value="Write a character here!" onkeyup="GetChar (event);"/>
where the event would give an error and clear the last character if the value is not a number:
<script type="text/javascript">
function GetChar (event){
var keyCode = ('which' in event) ? event.which : event.keyCode;
var yourChar = String.fromCharCode();
if (yourChar != "0" &&
yourChar != "1" &&
yourChar != "2" &&
yourChar != "3" &&
yourChar != "4" &&
yourChar != "5" &&
yourChar != "6" &&
yourChar != "7" &&
yourChar != "8" &&
yourChar != "9")
{
alert ('The character was not a number');
var source = event.target || event.srcElement;
source.value = source.value.substring(0,source.value-2);
}
}
</script>
Obviously you could do that with regex, too, but I took the lazy way out.
Since then you would know that only numbers could be in the box, you should be able to just use eval():
dots = eval(dots) + 5;
I need to make sure that my string is a number and for doing that, I was using isNaN function and everything was working but I got a problem when I typed in my input field '0e1'.
I was wondering what's the best way to check if my string is a number and without scientific notation
Try using regex. Here are some examples. The result is null if no match was found.
alert("0e1".match(/^[-+]?[0-9]*\.?[0-9]+$/)) // null
alert("1".match(/^[-+]?[0-9]*\.?[0-9]+$/)) // 1
alert("-1".match(/^[-+]?[0-9]*\.?[0-9]+$/)) // -1
alert("1.0".match(/^[-+]?[0-9]*\.?[0-9]+$/)) // 1.0
alert("-1.5".match(/^[-+]?[0-9]*\.?[0-9]+$/)) // -1.5
alert("-1.5 4".match(/^[-+]?[0-9]*\.?[0-9]+$/)) // null
If you want your input to only be an integer or float do this instead;
var input = '0e1';
if(!isNaN(input) && (parseInt(input, 10).toString() == input || parseFloat(input).toString() == input)){
//This is a valid number
}
Actually, the method you are using is fine. You have one problem with your code:
isNaN() should be !isNaN(). Remember, isNaN() checks if the number is NotaNumber. `!isNaN() checks if it IS a number.
isNaN(0e1) should return false because 0e1 is a number! I know, it's kind of confusing.
!isNaN(0e1) will return TRUE because !isNan() checks if a value IS a number.
I hope this helps.
isNaN() function determines whether a value is an illegal number, so if it is not a number. The good thing about isNaN function is, that is suportet by all browsers (ch, ie, ff, op, sf).
function myFunction() {
var a = isNaN(123) + "<br>";
var b = isNaN(-1.23) + "<br>";
var c = isNaN(123-456) + "<br>";
var d = isNaN("Hello") + "<br>";
var e = isNaN("2014/11/19") + "<br>";
var result = a + b + c + d + e;
document.getElementById("test").innerHTML = result;
}
So result would be: If value is a number return "False" if is not a number return "True".
You can test it on JsFiddle: isNaN()
I'm trying to make a simple addition tool to add 2 values together, I'm just having a little trouble with the NaN checking... would like to print "Please insert numbers only" if either A or B, or both are NaN.
function getTotal() {
var a = parseInt(document.addBoxes.boxA.value);
var b = parseInt(document.addBoxes.boxB.value);
if (total != NaN) {
total = a+b;
document.getElementById("total").innerHTML = "The sum is " + total + ".";
}
else if (a === NaN || b === NaN){
document.getElementById("total").innerHTML = "Please insert numbers only.";
}
else if (a === NaN && b === NaN){
document.getElementById("total").innerHTML = "Please insert numbers only.";
}
};
Also, if there is a performance-friendly way to do this, or a better method.
Thanks!
Checking each individual value for NaN is not required.
function getTotal() {
var a = parseInt(document.addBoxes.boxA.value);
var b = parseInt(document.addBoxes.boxB.value);
var total = a + b;
if (!isNaN(total)) {
document.getElementById("total").innerHTML = "The sum is " + total + ".";
} else {
document.getElementById("total").innerHTML = "Please insert numbers only.";
}
}
Several problems in your code.
Line 4: if (total != NaN) {
total hasn't been defined yet. You should define it in a var beforehand if you don't want to leak globals.
var total = a + b;
Also, NaN will never equal itself so this kind of equality is dangerous. Either use the built-in isNaN() function to check for NaN or (since you mentioned performance-friendly) you can skip the function invocation and use:
if (total !== total) {
Since NaN is the only thing in javascript that doesn't equal itself. Notice I'm using a strict not-equals, we don't want any coercion. This might be a bit too abstract and people who look at the code later (including yourself) might have forgotten this unique property of NaN so I'd prefix this conditional with a comment and perhaps a link to the MDN - Necessity of isNaN page.
Your code might end up looking something like simonzack's answer.
Thanks to some of the answers on this site, I built a function to validate an integer inside a prompt in javascript. I found out how to use isNaN and the result of % in order to meet my needs, but there must be something wrong, because is still not working: This function for validation needs to accept only integers, and as extra bonus, it will also accept a special keyword used for a different purpose later on in the program.
So, previously I had defined:
var value = prompt("Type an integer");
So after that, I made a call for the validation function, and that included three conditions: The validation warning would jump if:
1) The string is not a number
2) The string % 1 is not 0 (means is not an integer)
3) The string is not the special keyword ("extra") which is also valid as input.
The function needs to loop and keep showing the prompt until a valid data is written.
while (isNaN(value) == true && value % 1 != 0 && value != "extra") {
alert("Please, type an integer");
var value = prompt("Type an integer");
}
What am I doing wrong? Thank you so much for any ideas. I know the integer validation has been asked many times here, and here I got a few ideas, but I might be missing something...
You might be complicating things too much... A quick regular expression will do the trick.
while (!/^(\d+|extra)$/i.test(value)) {
...
}
You typed only one equal at
isNaN(value) = true
jsFiddle example
var int = 10;
var str = "10";
var isInt = function(value) {
return (str === 'extra' || !isNaN(parseInt(value, 16)) || /^\d+$/.test(value));
};
var isIntStrict = function(value) {
return (isInt(value) && typeof value !== 'string');
}
console.log('false', isInt('kirk'));
console.log('true', isInt(int));
console.log('true', isInt(str));
console.log('true', 'strict - int', isIntStrict(int));
console.log('false','strict - string', isIntStrict(str));
console.log('false','strict - string', isIntStrict('0x04'));
console.log('true','strict - string', isIntStrict(0x04));
I assume that for your purposes #elclanrs' answer is all you need here, and is the simplest and most straightforward, but just for completeness and dubious laughs, I'm pretty sure that the following would also do what you're looking for:
function isAnIntOrExtra(v) {
if (parseInt(+v) === +v && v !== '') {
return parseInt(+v);
}
else if (v === 'extra') {
return v;
}
else {
return false;
}
}
Fiddle here
These should all pass and return an integer in decimal notation:
'387' returns 387
'-4' returns -4
'0' returns 0
'2.4e3' returns 2400
'0xf4' returns 244
while these should all fail:
'4.5' returns false
'2.4e-3' returns false
'0xgc' returns false
'' returns false
'seven' returns false
And the magic-word 'extra' returns 'extra'
Of course, it'll "fail" miserably with values like '1,345', and will probably roll right over octal notation, treating it as though it were decimal notation (depending on the JavaScript engine?), but it could be tweaked to handle those situations as well, but really, you're better off with the regex.