What's the best way to detect if a number, is between two other numbers? Is there already a function to do this in the Math object?
There is no specific function, but you can do it like this:
lowNumber < yourNumber && yourNumber < highNumber
Though the code solution is fairly obvious, if you're going to use it a lot, you may want to implement it on Number.prototype for convenience:
Number.prototype.inRange = function( a,b ) {
var n = +this;
return ( n > a && n < b );
};
So you'd use it like this:
(5).inRange( 3, 7 ); // true
Example: http://jsfiddle.net/dTHQ3/
Um if it is greater than one and less than the other.
var num1 = 3;
var num2 = 5;
var x = 4;
var isBetween = (num1 < x && num2 > x);
if ( yournumber < highNumber && yournumber > lowNumber ){
// do something
} else {
// do something else
}
The only optimized way to do this is to guess which is more likely: Is the number your checking more likely to be lower than the lower bound, or is it more likely to be higher than the upper bound?
With this in mind, you can take advantage of short circuiting by placing the more likely failure check first (if it fails that, it won't test the less likely criteria). This is the only way to optimize it.
Even this will save you the smallest amount of time that is most likely not going to be noticed. Perhaps if you were making this check millions of times, you might save a fraction of a second over the alternative.
Related
I need to create a sequence of numbers using while or for that consists of the sum of the symbols of the number.
For example, I have a sequence from 1 to 10. In console (if I've already written a code) will go just 1, 2,3,4,5,6,7,8,9,1. If I take it from 30 to 40 in the console would be 3,4,5,6,7,8,9,10,11,12,13.
I need to create a code that displays a sum that goes from 1 to 100. I don't know how to do it but in console I need to see:
1
2
3
4
5
5
6
7
8
9
1
2
3
4
etc.
I've got some code but I got only NaN. I don't know why. Could you explain this to me?
for (let i = '1'; i <= 99; i++) {
let a = Number(i[0]);
let b = Number(i[1])
let b1 = Boolean(b)
if (b1 == false) {
console.log ('b false', a)
}
else {
console.log ('b true', a + b)
}
}
I hope you get what I was speaking about.
Although I like the accepted answer however from question I gather you were asking something else, that is;
30 become 3+0=3
31 become 3+1=4
37 becomes 3+7=10
Why are we checking for boolean is beyond the scope of the question
Here is simple snnipet does exactly what you ask for
for (let i = 30; i <= 40; i++) {
let x=i.toString();
console.log( 'numbers from ' +i + ' are added together to become '+ (Number(x[0])+Number((x[1])||0)))
}
what er are doing is exactly what Maskin stated begin with for loop then in each increment convert it to string so we can split it, this takes care of NAN issue.
you don't need to call to string just do it once as in let x then simply call the split as x[0] and so on.
within second number we have created a self computation (x[1])||0) that is if there is second value if not then zero. following would work like charm
for (let i = 1; i <= 10; i++) {
let x=i.toString();
console.log( 'numbers from ' +i + ' are added together to become '+ (Number(x[0])+Number((x[1])||0)))
}
Did you observe what happens to ten
here is my real question and solution what if you Don't know the length of the digits in number or for what ever reason you are to go about staring from 100 on wards. We need some form of AI into the code
for (let i = 110; i <= 120; i++) {
let x= Array.from(String(i), Number);
console.log(
x.reduce(function(a, b){ return a + b;})
);
};
You simply make an array with Array.from function then use simple Array.reduce function to run custom functions that adds up all the values as sum, finally run that in console.
Nice, simple and AI
You got NaN because of "i[0]". You need to add toString() call.
for (let i = '1'; i <= 99; i++) {
let a = Number(i.toString()[0]);
let b = Number(i.toString()[1])
let b1 = Boolean(b)
if (b1 == false) {
console.log('b false', a)
} else {
console.log('b true', a + b)
}
}
So the way a for loop works is that you declare a variable to loop, then state the loop condition and then you ask what happens at the end of the loop, normally you increment (which means take the variable and add one to it).
When you say let i = '1', what you're actually doing, is creating a new string, which when you ask for i[0], it gives you the first character in the string.
You should look up the modulo operator. You want to add the number of units, which you can get by dividing by 10 and then casting to an int, to the number in the tens, which you get with the modulo.
As an aside, when you ask a question on StackOverflow, you should ask in a way that means people who have similar questions to you can find their answers.
Beginning JavaScript learner here...
I'm working through Adrian Neumann's Simple Programming Problems and my question is about number 6 in the elementary exercises.
Write a program that asks the user for a number n and gives him the possibility to choose between computing the sum and computing the product of 1,…,n.
// var myArray = []; // for testing
var mySum = 0;
var userNum = prompt("What is your number? ");
var userChoice = prompt("Would you like to add up (+) or multiply (*) all the numbers from 1 to your number? Please enter (+) or (*): ");
if (userChoice == "+") {
for (var i = userNum; i > 0; i--) {
mySum += +i;
}
console.log("Your answer is " + mySum);
} else if (userChoice == "*") {
for (var i = userNum; i > 0; i--) {
mySum *= +i;
// myArray.push(i); // for testing
}
console.log("Your answer is " + mySum);
// console.log(myArray); // for testing
}
When entering values for multiplication, the answer is always 0. Obviously, I thought 0 was being included in the iteration, so I setup an empty array myArray, and pushed all the numbers to the array using myArray.push(i);... 0 was never included as a value in the array.
Other than some obvious form-validation considerations, can anyone tell me what I'm missing? Why is my answer always 0?
Note: The sum section of the code seems to work brilliantly.
Please note I'm a beginniner to JavaScript, so if you'd like to comment, let me know WHY you changed the code the way you do, rather than simply spitting back code to me. That's a big help, thanks.
Well, you initialize mySum to 0 so in every iteration of the loop you'll multiplying i by zero and save the result (again, zero) back into mySum. For multiplication you'd have to start at one.
You didn't set mySum to 1 before multiplication. 0*i = 0.
I have this function.
Calculations.add(this, //CONTEXT
function () { //CALUCATE
this.position.x += (this.movementSpeed.x / 10);
},
function () { //HAVE CALCULATED
return (this.position.x === (tempX + this.movementSpeed.x));
}
);
I have run the result, but sometime the result is wrong. Cause I know that if it calculate 10 times, then the the HAVE CALCULATED whould be true.
But sometimes it never is... And that kills my app.
Let us say that the result should give 138, then after the calculation it give me 138.000000000006 which is not 138 and the HAVE CALCULATED is false..
How can I manage this= I can't use round, because it should be able to return 138.5, if the end-result is that.
Hope you understand my question.
Always floating point = comparisons should be done like this:
Math.abs( a - b ) < 1e-6
where 1e-6 is an arbitrary error threshold that you determine in advance
You should never compare floating point values this way. (The link from Waleed Khan in the comments gives a good explanation why this happens)
Instead you can do something like this to check equality of a and b:
if (a < b + 0.0001 && a > b - 0.0001) {
// values are "equal"
}
You could round to a certain number of digits, from another answer on SO use something like this:
function roundNumber(n, digits) {
var multiple = Math.pow(10, digits);
return Math.round(n * multiple) / multiple;;
}
This way you do not require fancy comparisons.
I did a rewrite of the code I submitted yesterday based on suggestions from others. I now have this but still can't seem to get it to work with greater than less than. I can add/substract the 2 numbers and get a valid answers. I can't get a > < to work however. Hoping someone can offer some additional help keeping it within this format of "If statements".
if ((input.search("what is greater")!= -1) && (input.search(/\d{1,10}/)!=-1) && (input.search(/\d{1,10}/)!=-1))
{var numbersInString = input.match(/\d+/g);
var num1 = parseInt( numbersInString[0], 10 );
var num2 = parseInt( numbersInString[1], 10 );
if (num1 < num2) document.result.result.value = ""+num1+" is less than "+num2+"";
if (num1 > num2) document.result.result.value = ""+num1+" is greater than "+num2+"";
if (num1 = num2) document.result.result.value = "Both numbers are equal";
return true;}
It sounds like you want to manipulate a number in two ways:
1) You want to refer to the individual characters.
2) You want to compare the number to another number and see if one is greater than another.
If you have a string called input, then you can use the function parseInt(input, 10) to convert it from a string to the number represented by that string.
If you want to get just the first two characters, you can use the substring function.
The important thing to keep in mind is that to the computer, the string '12345' and the number 12345 are completely different. The computer has a completely different set of operations that it will perform on each.
also, #albin is correct to point out that putting semicolons after your if statements is wrong.
The output of the match method is an array of strings, so I think you are NOT comparing numbers but strings. Try doing this before comparing your numbers.
var num1 = parseInt( numbersInString[0], 10 );
var num2 = parseInt( numbersInString[1], 10 );
And then compare num1 and num2.
http://jsfiddle.net/qt3RW/
Simple input box:
<input id="input1" value="Is 6 greater than 5"></input>
Parser find 'Is # greater than #' where # is digit and alert this digits:
var IsStringValid = $("#input1").val().match(/Is \d greater than \d/g);
alert(IsStringValid);
if(IsStringValid){
var values = $("#input1").val().match(/\d/g);
for(var i = 0; i < values.length; i++){
alert(values[i])
}
}
jsFiddle: http://jsfiddle.net/Mw4j2/6/
Trying to change attributes to a selector if the seconds count is 10 or under.
I'm using
var returnSecondsNumber = $('.countdownSecond > .countSeconds > .position:first-child > .digit').text() + $('.countdownSecond > .countSeconds > .position:nth-child(2) > .digit').text();
To grab the numbers from both spans and returns it as 16/15/14/etc.
Now I need do something if this numeric is under 10.
e.g.
if (returnsSecondsNumber <= 10)
{ $(this).addClass('urgent');
}, else { //do something
}
I've tried taking a look at parseInt with no success. Any help would be much appreciated!
Thanks.
Two things:
First, you need to move the code that constructs "returnSecondsNumber" into the callback function(s) of whichever timers you want to monitor.
Second, just use parseInt():
var numericVal = parseInt(returnsSecondsNumber, 10);
if (!isNaN(numericVal) && numericVal < 10) {
// do whatever
}
Try
if(!isNaN(parseInt(returnsSecondsNumber )) && returnsSecondsNumber < 11)
//Do stuff...
One thing to keep in mind is that if the value of returnsSecondNumber is a starts with a number that will be returned instead of NaN