Javascript - Calculate and compare - javascript

I'm learning JS, and in my practice I can't get the second part of my script to work for me.
I have 3 inputs (#ancho - #fondo - #alto), where I write integers number for a multiplication between them, followed by a division. This part works fine
Now the problem:
In the second part, I want to compare if the value "r =" is greater or less than the number written (por the user) in the input #peso, but it doesn't work for me.
What am I doing wrong here?
See the DEMO in JSFiddle
Thanks in advance!
HTML:
<input id="ancho"> <!-- Example value="22" -->
<input id="fondo"> <!-- Example value="20" -->
<input id="alto"> <!-- Example value="16" -->
<input id="peso"> <!-- Example value="3" -->
<div id="resultado"></div>
<div id="hacercalculo" onclick="calcular();comparar()">Calcular</div>
<!--css display none-->
<div id="uno">1</div>
<div id="dos">2</div>
<div id="tres">3</div>
jQuery:
https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js
Script:
// Calculate - This part works fine
function calcular(){
v1 = document.getElementById("ancho").value;
v2 = document.getElementById("fondo").value;
v3 = document.getElementById("alto").value;
r = v1*v2*v3/4000;
//document.getElementById("resultado").value = r;
document.getElementById("resultado").innerHTML = r;
};
//=============
// Compare - This, It does not work for me
function comparar() {
var camp1= document.getElementById("resultado");
var camp2= document.getElementById("peso");
//if (camp1.value >= 0 && camp2.value <= 3) {
//if (camp1.innerText >= 0 && camp2.innerText <= 3) {
//if (camp1.innerHTML >= 0 && camp2.value <= 3) {
if (camp1.innerText >= 0 && camp2.value <= 3) {
$("#uno").show(); // This, It does not work for me
}
};

Just a small amendment to "if statement" in your comparar() function.
textContent has to be converted to number.
if (Number(camp1.textContent) >= 0 && camp2.value <= 3) {
$("#uno").show();
}
Please refer to this code pen example after this change,
https://codepen.io/SathishVel/pen/KKVMvqj

If r is greater than or less than peso then r != peso. The following comparar function should handle the second part.
function comparar() {
var camp1= document.getElementById("resultado").innerHTML;
var camp2= document.getElementById("peso").value;
if (Number(camp1) != Number(camp2)) {
$("#uno").show(); // condition met hence #uno rendered.
}
};

There was some issues with your code hence why i didn't work
first you should get the value using textContent
var camp1= document.getElementById("resultado").textContent;
second you are retrieving the value twice
var camp2= document.getElementById("peso").value;
if (camp1 >= 0 && camp2.value <= 3)
it should be (camp1 >= 0 && camp2 <= 3)
finally for your code to work your if statement has to return a value
if (camp1.innerText >= 0 && camp2.value <= 3) {
return console.log('..show one') // use the return keyword to return value
}
try this
function comparar() {
var camp1= document.getElementById("resultado").textContent;
console.log(camp1)
var camp2= document.getElementById("peso").value;
console.log(camp2)
if (camp1 >= 0 && camp2 <= 3) {
$("#uno").show();
}
}
</script>

From what you said you need to check if the values ​​are in a certain range and also want to check if it has decimal places or not, so I will create two functions that do these two checks.
Function to check if a value is in a certain range:
function interval(a, b, c) {
return ((b - a) * (b - c) <= 0)
}
Example of use:
interval(2, 5, 6) // true (2 < 5 < 6)
interval(2, 1, 6) // false (2 < 1 < 6), false because 2 < 1 is false
interval(2, 7, 6) // false (2 < 7 < 6), false because 7 < 6 is false
Font: Check if a value is within a range of numbers credits Alexander
Function to check if the number has decimal places:
function isDecimal(a) {
if(Number(a) == Math.floor(a)) {
return false
} else {
return true
}
}
Example of use:
isDecimal(2) // false
isDecimal(2.2) // true
Note: In your algorithm you are using the following variables:
var camp1= document.getElementById("resultado");
var camp2= document.getElementById("peso");
They are in string format, so you need to transform them into numbers before using them in these functions, so below them do:
camp1 = Number(camp1)
camp2 = Number(camp2)

Related

Checking divisibility and converting digits into text

Check the divisibility of 2, 3, and both 2 and 3
Divisible by 2 - print x
Divisible by 3 - print y
Divisible by 2 and 3 - print xy
let num = prompt('1-1000');
if (num %2 == 0 )
{
console.log("X")
}
if (num %3 == 0 )
{
console.log("Y")
}
if (num %3 == 0 && num %2 ==0)
{
console.log("XY")
}
Example:
Input: 6
Output:
X
Y
XY
How to make it not print X, Y but XY?
What needs to be done so that several digits to be checked after the decimal point can be entered and then converted to the appropriate letters?
There are a couple of ways you could do this.
One way would be to use a ternary operator to output the values X and/or Y. This will have X logged only when divisible by 2, and Y only logged when divisible by 3. If it is divisible by both, both are shown but their conditions are independent of each other. And using template literals it is concatenated into 1 value.
let num = prompt('1-1000');
console.log(`${(num%2==0)?"X":""}${(num%3==0)?"Y":""}`);
Alternatively, you could use something like what was mentioned in the comments. If you convert the code to a function, you can move the final if statement to the top and use exit/return statements to return only 1 of the values (whichever applies).
const _Check = () => {
let num = prompt('1-1000');
if(num % 3 == 0 && num % 2 == 0) return "XY";
if(num % 2 == 0 ) return "X";
if(num % 3 == 0 ) return "Y";
return "";
}
console.log(_Check());
EDIT
In reponse to a comment by OP: checking for multiple numbers could be done by splitting the value input by the user and then looping through those values.
If the user will be inputting each number separated by a space, you can use the split() method with a space as the separator. And then use forEach() to loop through each number and apply the code/logic we have used earlier.
Example Using ternary operator and template literals:
let num = prompt('1-1000')
num.split(" ").forEach(n => {
console.log(`${(n%2==0)?"X":""}${(n%3==0)?"Y":""}`);
})
Example using a function and return statements:
let num = prompt('1-1000')
const _Check = n => {
if(n %3 == 0 && n %2 ==0) return "XY";
if(n %2 == 0 ) return "X";
if(n %3 == 0 ) return "Y";
return "";
}
num.split(" ").forEach(n => {
console.log(_Check(n));
})

How to display list of numbers based on condition in javascript

I would like to know how to get the list of numbers based on two condition
number should be divisible by 3
number should not end with 3
How to implement the list within 50 numbers in javascript
Expected Output
6,9,12,15...45
My attempt
function getNumbers() {
var result = [];
for (var i = 0; i < 50; i++) {
if (i % 2 == 0) {
return
} else {
result.push(i);
return result.toString()
}
}
}
console.log(getNumbers())
This seems to work to specs - your specs says it should start at 6 and not at 1
const numbers = [...Array(50).keys()].
filter(num => num !== 0 && num%3 === 0 && !String(num).endsWith("3"))
console.log(numbers)
NOTE: You can change [...Array(50).keys()] to [...Array(50).keys()].slice(1) if you want to avoid the test for 0
You can do that with a check if the modulo of 3 is 0 and the modulo of 10 is not 3. If you want to beautify the code you can combine this answer with mplungjan answer, but i wanted to show a mathematical alternative of the !String(num).endsWith("3") method provided by mplungjan.
I started your iteration at 1 instead of 0 to avoid 0 being put into the array. I also corrected your return statements.
function getNumbers() {
var result = [];
for (var i = 1; i < 50; i++) {
if (i % 3 === 0 && i % 10 !== 3) {
result.push(i);
}
}
return result;
}
console.log(getNumbers())

How do I know if a number is odd or even in JS? [duplicate]

Can anyone point me to some code to determine if a number in JavaScript is even or odd?
Use the below code:
function isOdd(num) { return num % 2;}
console.log("1 is " + isOdd(1));
console.log("2 is " + isOdd(2));
console.log("3 is " + isOdd(3));
console.log("4 is " + isOdd(4));
1 represents an odd number, while 0 represents an even number.
Use the bitwise AND operator.
function oddOrEven(x) {
return ( x & 1 ) ? "odd" : "even";
}
function checkNumber(argNumber) {
document.getElementById("result").innerHTML = "Number " + argNumber + " is " + oddOrEven(argNumber);
}
checkNumber(17);
<div id="result" style="font-size:150%;text-shadow: 1px 1px 2px #CE5937;" ></div>
If you don't want a string return value, but rather a boolean one, use this:
var isOdd = function(x) { return x & 1; };
var isEven = function(x) { return !( x & 1 ); };
You could do something like this:
function isEven(value){
if (value%2 == 0)
return true;
else
return false;
}
function isEven(x) { return (x%2)==0; }
function isOdd(x) { return !isEven(x); }
Do I have to make an array really large that has a lot of even numbers
No. Use modulus (%). It gives you the remainder of the two numbers you are dividing.
Ex. 2 % 2 = 0 because 2/2 = 1 with 0 remainder.
Ex2. 3 % 2 = 1 because 3/2 = 1 with 1 remainder.
Ex3. -7 % 2 = -1 because -7/2 = -3 with -1 remainder.
This means if you mod any number x by 2, you get either 0 or 1 or -1. 0 would mean it's even. Anything else would mean it's odd.
This can be solved with a small snippet of code:
function isEven(value) {
return !(value % 2)
}
Hope this helps :)
In ES6:
const isOdd = num => num % 2 == 1;
Like many languages, Javascript has a modulus operator %, that finds the remainder of division. If there is no remainder after division by 2, a number is even:
// this expression is true if "number" is even, false otherwise
(number % 2 == 0)
Similarly, if there is a remainder of 1 after division by 2, a number is odd:
// this expression is true if "number" is odd, false otherwise
(number % 2 == 1)
This is a very common idiom for testing for even integers.
With bitwise, codegolfing:
var isEven=n=>(n&1)?"odd":"even";
Use my extensions :
Number.prototype.isEven=function(){
return this % 2===0;
};
Number.prototype.isOdd=function(){
return !this.isEven();
}
then
var a=5;
a.isEven();
==False
a.isOdd();
==True
if you are not sure if it is a Number , test it by the following branching :
if(a.isOdd){
a.isOdd();
}
UPDATE :
if you would not use variable :
(5).isOdd()
Performance :
It turns out that Procedural paradigm is better than OOP paradigm .
By the way , i performed profiling in this FIDDLE . However , OOP way is still prettiest .
A simple function you can pass around. Uses the modulo operator %:
var is_even = function(x) {
return !(x % 2);
}
is_even(3)
false
is_even(6)
true
if (X % 2 === 0){
} else {
}
Replace X with your number (can come from a variable). The If statement runs when the number is even, the Else when it is odd.
If you just want to know if any given number is odd:
if (X % 2 !== 0){
}
Again, replace X with a number or variable.
<script>
function even_odd(){
var num = document.getElementById('number').value;
if ( num % 2){
document.getElementById('result').innerHTML = "Entered Number is Odd";
}
else{
document.getElementById('result').innerHTML = "Entered Number is Even";
}
}
</script>
</head>
<body>
<center>
<div id="error"></div>
<center>
<h2> Find Given Number is Even or Odd </h2>
<p>Enter a value</p>
<input type="text" id="number" />
<button onclick="even_odd();">Check</button><br />
<div id="result"><b></b></div>
</center>
</center>
</body>
Many people misunderstand the meaning of odd
isOdd("str") should be false.
Only an integer can be odd.
isOdd(1.223) and isOdd(-1.223) should be false.
A float is not an integer.
isOdd(0) should be false.
Zero is an even integer (https://en.wikipedia.org/wiki/Parity_of_zero).
isOdd(-1) should be true.
It's an odd integer.
Solution
function isOdd(n) {
// Must be a number
if (isNaN(n)) {
return false;
}
// Number must not be a float
if ((n % 1) !== 0) {
return false;
}
// Integer must not be equal to zero
if (n === 0) {
return false;
}
// Integer must be odd
if ((n % 2) !== 0) {
return true;
}
return false;
}
JS Fiddle (if needed): https://jsfiddle.net/9dzdv593/8/
1-liner
Javascript 1-liner solution. For those who don't care about readability.
const isOdd = n => !(isNaN(n) && ((n % 1) !== 0) && (n === 0)) && ((n % 2) !== 0) ? true : false;
You can use a for statement and a conditional to determine if a number or series of numbers is odd:
for (var i=1; i<=5; i++)
if (i%2 !== 0) {
console.log(i)
}
This will print every odd number between 1 and 5.
Just executed this one in Adobe Dreamweaver..it works perfectly.
i used if (isNaN(mynmb))
to check if the given Value is a number or not,
and i also used Math.abs(mynmb%2) to convert negative number to positive and calculate
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body bgcolor = "#FFFFCC">
<h3 align ="center"> ODD OR EVEN </h3><table cellspacing = "2" cellpadding = "5" bgcolor="palegreen">
<form name = formtwo>
<td align = "center">
<center><BR />Enter a number:
<input type=text id="enter" name=enter maxlength="10" />
<input type=button name = b3 value = "Click Here" onClick = compute() />
<b>is<b>
<input type=text id="outtxt" name=output size="5" value="" disabled /> </b></b></center><b><b>
<BR /><BR />
</b></b></td></form>
</table>
<script type='text/javascript'>
function compute()
{
var enter = document.getElementById("enter");
var outtxt = document.getElementById("outtxt");
var mynmb = enter.value;
if (isNaN(mynmb))
{
outtxt.value = "error !!!";
alert( 'please enter a valid number');
enter.focus();
return;
}
else
{
if ( mynmb%2 == 0 ) { outtxt.value = "Even"; }
if ( Math.abs(mynmb%2) == 1 ) { outtxt.value = "Odd"; }
}
}
</script>
</body>
</html>
When you need to test if some variable is odd, you should first test if it is integer. Also, notice that when you calculate remainder on negative number, the result will be negative (-3 % 2 === -1).
function isOdd(value) {
return typeof value === "number" && // value should be a number
isFinite(value) && // value should be finite
Math.floor(value) === value && // value should be integer
value % 2 !== 0; // value should not be even
}
If Number.isInteger is available, you may also simplify this code to:
function isOdd(value) {
return Number.isInteger(value) // value should be integer
value % 2 !== 0; // value should not be even
}
Note: here, we test value % 2 !== 0 instead of value % 2 === 1 is because of -3 % 2 === -1. If you don't want -1 pass this test, you may need to change this line.
Here are some test cases:
isOdd(); // false
isOdd("string"); // false
isOdd(Infinity); // false
isOdd(NaN); // false
isOdd(0); // false
isOdd(1.1); // false
isOdd("1"); // false
isOdd(1); // true
isOdd(-1); // true
Using % will help you to do this...
You can create couple of functions to do it for you... I prefer separte functions which are not attached to Number in Javascript like this which also checking if you passing number or not:
odd function:
var isOdd = function(num) {
return 'number'!==typeof num ? 'NaN' : !!(num % 2);
};
even function:
var isEven = function(num) {
return isOdd(num)==='NaN' ? isOdd(num) : !isOdd(num);
};
and call it like this:
isOdd(5); // true
isOdd(6); // false
isOdd(12); // false
isOdd(18); // false
isEven(18); // true
isEven('18'); // 'NaN'
isEven('17'); // 'NaN'
isOdd(null); // 'NaN'
isEven('100'); // true
A more functional approach in modern javascript:
const NUMBERS = "nul one two three four five six seven ocho nueve".split(" ")
const negate = f=> (...args)=> !f(...args)
const isOdd = n=> NUMBERS[n % 10].indexOf("e")!=-1
const isEven = negate(isOdd)
One liner in ES6 just because it's clean.
const isEven = (num) => num % 2 == 0;
Subtract 2 to it recursively until you reach either -1 or 0 (only works for positive integers obviously) :)
Every odd number when divided by two leaves remainder as 1 and every even number when divided by zero leaves a zero as remainder. Hence we can use this code
function checker(number) {
return number%2==0?even:odd;
}
How about this...
var num = 3 //instead get your value here
var aa = ["Even", "Odd"];
alert(aa[num % 2]);
This is what I did
//Array of numbers
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10,32,23,643,67,5876,6345,34,3453];
//Array of even numbers
var evenNumbers = [];
//Array of odd numbers
var oddNumbers = [];
function classifyNumbers(arr){
//go through the numbers one by one
for(var i=0; i<=arr.length-1; i++){
if (arr[i] % 2 == 0 ){
//Push the number to the evenNumbers array
evenNumbers.push(arr[i]);
} else {
//Push the number to the oddNumbers array
oddNumbers.push(arr[i]);
}
}
}
classifyNumbers(numbers);
console.log('Even numbers: ' + evenNumbers);
console.log('Odd numbers: ' + oddNumbers);
For some reason I had to make sure the length of the array is less by one. When I don't do that, I get "undefined" in the last element of the oddNumbers array.
I'd implement this to return a boolean:
function isOdd (n) {
return !!(n % 2);
// or ((n % 2) !== 0).
}
It'll work on both unsigned and signed numbers. When the modulus return -1 or 1 it'll get translated to true.
Non-modulus solution:
var is_finite = isFinite;
var is_nan = isNaN;
function isOdd (discriminant) {
if (is_nan(discriminant) && !is_finite(discriminant)) {
return false;
}
// Unsigned numbers
if (discriminant >= 0) {
while (discriminant >= 1) discriminant -= 2;
// Signed numbers
} else {
if (discriminant === -1) return true;
while (discriminant <= -1) discriminant += 2;
}
return !!discriminant;
}
By using ternary operator, you we can find the odd even numbers:
var num = 2;
result = (num % 2 == 0) ? 'even' : 'odd'
console.log(result);
Another example using the filter() method:
let even = arr.filter(val => {
return val % 2 === 0;
});
// even = [2,4,6]
So many answers here but i just have to mention one point.
Normally it's best to use the modulo operator like % 2 but you can also use the bitwise operator like & 1. They both would yield the same outcome. However their precedences are different. Say if you need a piece of code like
i%2 === p ? n : -n
it's just fine but with the bitwise operator you have to do it like
(i&1) === p ? n : -n
So there is that.
this works for arrays:
function evenOrOdd(numbers) {
const evenNumbers = [];
const oddNumbers = [];
numbers.forEach(number => {
if (number % 2 === 0) {
evenNumbers.push(number);
} else {
oddNumbers.push(number);
}
});
console.log("Even: " + evenNumbers + "\nOdd: " + oddNumbers);
}
evenOrOdd([1, 4, 9, 21, 41, 92]);
this should log out:
4,92
1,9,21,41
for just a number:
function evenOrOdd(number) {
if (number % 2 === 0) {
return "even";
}
return "odd";
}
console.log(evenOrOdd(4));
this should output even to the console
A Method to know if the number is odd
let numbers = [11, 20, 2, 5, 17, 10];
let n = numbers.filter((ele) => ele % 2 != 0);
console.log(n);

What is the best way to check >= and <= in Javascript?

I have a number.
I then have an if statement that I want to go like this:
if (5 <= variable <= 10)
So if the number is between 5 and 10, the statement should be true.
What's the best way to go about this?
Thanks.
it is
if (5 <= variable && variable <= 10)
if ((variable >= 5) && (variable <= 10)) works.
If you do this frequently, consider defining a bounds function:
function inBounds(value, min, max){
return ((value >= min) && (value <= max));
}
Actually, if ( 5>= variable >= 10 ) means if(false)
if you means variable between 5, 10 it should be 5 <= variable <=10, and in javascript, the best convention is const value at left, which is from c language if (v=1), if (1=v) problem. so the best is:
if (5 <= variable && 10 >= variable) {
It is my understanding that at the first conditional false, it stops the checking and moves to the next statement.
Given that, you should examine the most often false condition and put it first.
if ((variable >= 5) && (variable <= 10))
if it is more likely to be less than 4 or
if ((variable <= 10) && (variable >= 5))
if the failure of 10 or greater is more likely to occur.

Multiple Logical Operators in javascript

I want to check the following
1: Is x a number
2. If x is less that 5 or greater than 15, sound alert
3. If all is ok, callMe()
var x = 10;
if (isNaN(x) && ((x < 5) || (x > 15))) {
alert('not allowed')
}
else
{
callMe();
}
What am I doing wrong?
var x = 10;
if (isNaN(x) || (x < 5) || (x > 15)) {
alert('not allowed')
}
else
{
callMe();
}
This way, if x is not a number you go directly to the alert. If it is a number, you go to the next check (is x < 5), and so on.
All the other answers about the && vs || are correct, I just wanted to add another thing:
The isNaN() function only checks whether the parameter is the constant NaN or not. It doesn't check whether the parameter is actually number or not. So:
isNaN(10) == false
isNaN('stackoverflow') == false
isNaN([1,2,3]) == false
isNaN({ 'prop' : 'value'}) == false
isNaN(NaN) == true
In other words, you cannot use it to check whether a given variable contains a number or not. To do that I'd suggest first running the variable through parseInt() or parseFloat() depending on what values you expect there. After that check for isNaN(), because these functions return only numbers or NaN. Also this will make sure that if you have a numeric string then it is also treated like a number.
var x = 10;
if (isNaN(x) || (x < 5) || (x > 15)) {
alert('not allowed')
}
else
{
callMe();
}

Categories

Resources