Check if number exists in a number - javascript

I have an odd situation, I think...
I am writing some jquery/javascript code to validate numbers and I need to check if a given int exists within the entered number.
So for instance if the number I am checking against is 15 and the persons types in a 1, I need to check and see if that 1 exists within the 15, if it does then return true else return false.
I tried .stringOf but that of course only works on strings.
Any thoughts? Sorry if it is a super simple answer. Thanks in advance.
So far:
var Quantity = parseFloat(entered_value); // 1
var max = 15;
if(max.indexOf(Quantity) >= 0){
qty = Quantity;
}else{
qty = max;
}

var Quantity = parseFloat(entered_value); // 1
var max = 15;
if(max.toString().indexOf(Quantity.toString()) >= 0){
qty = Quantity;
}else{
qty = max;
}

Just to type out Reason's suggestion
var num = 1,
max = 15,
isSubString = (max+'').indexOf(num) > -1;
if ( isSubString ) {
// Num is a sub string of max
}

Related

I cant get my code to check if a number is already in a array | JavaScript

var usedNumbers = []
var counter = 0
while(counter < 9){
var math = Math.floor(Math.random() * 9)
if(math != usedNumbers){
usedNumbers[counter] = math
counter++
}
}
console.log(usedNumbers)
i am really bad at explaining and really new to coding but i will do my best
i want my piece of code to create a random number, check if that number is used before and then put it in the array so i can use it later.
but for some reason the if statement is always true so it doesnt check for duplicates
if someone can explain what i did wrong and how to fix it that would be great
You could take a Set and check only the size of it.
const numbers = new Set;
while (numbers.size < 9) numbers.add(Math.floor(Math.random() * 9));
console.log(...numbers);
You can use the array method .includes
var usedNumbers = []
var counter = 0
while(counter < 9){
var math = Math.floor(Math.random() * 9)
if(!usedNumbers.includes(math)){
usedNumbers[counter] = math
counter++
}
}
console.log(usedNumbers.sort())
Here is a functional and recursive way of doing it.
const saveNums = (currentNum, size, result) => {
if (result.length >= size) {
return result;
}
const newResult = result.includes(currentNum) ? result : [...result, currentNum];
return saveNums(Math.floor(Math.random() * size), size, newResult);
};
console.log(saveNums(Math.floor(Math.random() * 9), 9, []));

Why does if statement not work and make my element disappear using display: none?

I am building a tip calculator and I couldn't make the if statement in my function work it just skips to calculating.
function calculate() {
var bill = parseInt(document.getElementById("bill").value);
var tip = parseInt(document.getElementById("tip").value) * .01;
var persons = parseInt(document.getElementById("persons").value);
if (bill == "" || tip == "") {
alert("Please enter value");
return;
};
if (persons == "" || persons <= 1) {
persons = 1;
document.getElementById("perPerson").style.display = "none";
} else {
}
let totalTipPer = (bill * tip) / persons;
let totalPer = (bill + (tip * 100)) / persons;
let totalTip = bill * tip;
let total = bill + (tip * 100);
totalTipPer = totalTipPer.toFixed(2);
totalPer = totalPer.toFixed(2);
total = total.toFixed(2);
totalTip = totalTip.toFixed(2);
document.getElementById("total-tip/person").innerHTML = totalTipPer;
document.getElementById("total-price/person").innerHTML = totalPer;
document.getElementById("total-tip").innerHTML = totalTip;
document.getElementById("total-price").innerHTML = total;
}
document.getElementById("calculate").onclick = function () {
calculate();
document.getElementById('results').style.display = 'block';
}
I expect the div encapsulating Tip Amount per person and total per person and to not appear when the input value of persons is empty.
Function parseInt returns 'An integer number parsed from the given string. If the first character cannot be converted to a number, NaN is returned.'
if you rpovide an empty value ('') it will return
NaN which is not equal to anything, even itself.
there are several ways to fix this:
check if it is a NaN with Number.isNaN(var)
use an intermediate value like var personsValue and check if it is equal to empty string ''.
use Hybrid suggested solution and assign a 0
value for falsy value('', undefined, n
ull etc...)
The issue is that persons becomes NaN, since if the value is left blank, "" becomes NaN when it is run through parseInt().
The way to fix this is by defaulting it to 0 if the field is left blank.
var persons = parseInt(document.getElementById("persons").value || 0);
as others pointed out parseInt is returning NaN if the field is blank, but this will also happen if the user inputs $5.00 for example.
Here's one way to make sure the value can be converted to a number before doing so.
// This function determines if a JavaScript String can be converted into a number
function is_numeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function calculate() {
// first put the input values into separate variables
billValue = document.getElementById("bill").value;
tipValue = document.getElementById("tip").value;
personsValue = document.getElementById("persons").value;
// use the is_numeric() function above to check if the values can be converted to numeric
if (!is_numeric(billValue) || !is_numeric(tipValue)) {
alert("Please enter values for bill and tip");
return;
}
// the rest of your code here
}
Hope this helps.

Advice on how to code Luhn Credit Card validation with Javascript?

I'm pretty awful at Javascript as I've just started learning.
I'm doing a Luhn check for a 16-digit credit card.
It's driving me nuts and I'd just appreciate if someone looked over it and could give me some help.
<script>
var creditNum;
var valid = new Boolean(true);
creditNum = prompt("Enter your credit card number: ");
if((creditNum==null)||(creditNum=="")){
valid = false;
alert("Invalid Number!\nThere was no input.");
}else if(creditNum.length!=16){
valid = false;
alert("Invalid Number!\nThe number is the wrong length.");
}
//Luhn check
var c;
var digitOne;
var digitTwo;
var numSum;
for(i=0;i<16;i+2){
c = creditNum.slice(i,i+1);
if(c.length==2){
digitOne = c.slice(0,1);
digitTwo = c.slice(1,2);
numSum = numSum + (digitOne + digitTwo);
}else{
numSum = numSum + c;
}
}
if((numSum%10)!=0){
alert("Invalid Number!");
}else{
alert("Credit Card Accepted!");
}
</script>
The immediate problem in your code is your for loop. i+2 is not a proper third term. From the context, you're looking for i = i + 2, which you can write in shorthand as i += 2.
It seems your algorithm is "take the 16 digits, turn them into 8 pairs, add them together, and see if the sum is divisible by 10". If that's the case, you can massively simplify your loop - you never need to look at the tens' place, just the units' place.
Your loop could look like this and do the same thing:
for (i = 1; i < 16; i +=2) {
numSum += +creditNum[i];
}
Also, note that as long as you're dealing with a string, you don't need to slice anything at all - just use array notation to get each character.
I added a + in front of creditNum. One of the issues with javascript is that it will treat a string as a string, so if you have string "1" and string "3" and add them, you'll concatenate and get "13" instead of 4. The plus sign forces the string to be a number, so you'll get the right result.
The third term of the loop is the only blatant bug I see. I don't actually know the Luhn algorithm, so inferred the rest from the context of your code.
EDIT
Well, it would have helped if you had posted what the Luhn algorithm is. Chances are, if you can at least articulate it, you can help us help you code it.
Here's what you want.
// Luhn check
function luhnCheck(sixteenDigitString) {
var numSum = 0;
var value;
for (var i = 0; i < 16; ++i) {
if (i % 2 == 0) {
value = 2 * sixteenDigitString[i];
if (value >= 10) {
value = (Math.floor(value / 10) + value % 10);
}
} else {
value = +sixteenDigitString[i];
}
numSum += value;
}
return (numSum % 10 == 0);
}
alert(luhnCheck("4111111111111111"));
What this does is go through all the numbers, keeping the even indices as they are, but doubling the odd ones. If the doubling is more than nine, the values of the two digits are added together, as per the algorithm stated in wikipedia.
FIDDLE
Note: the number I tested with isn't my credit card number, but it's a well known number you can use that's known to pass a properly coded Luhn verification.
My below solution will work on AmEx also. I submitted it for a code test a while ago. Hope it helps :)
function validateCard(num){
var oddSum = 0;
var evenSum = 0;
var numToString = num.toString().split("");
for(var i = 0; i < numToString.length; i++){
if(i % 2 === 0){
if(numToString[i] * 2 >= 10){
evenSum += ((numToString[i] * 2) - 9 );
} else {
evenSum += numToString[i] * 2;
}
} else {
oddSum += parseInt(numToString[i]);
}
}
return (oddSum + evenSum) % 10 === 0;
}
console.log(validateCard(41111111111111111));
Enjoy - Mitch from https://spangle.com.au
#Spangle, when you're using even and odd here, you're already considering that index 0 is even? So you're doubling the digits at index 0, 2 and so on and not the second position, fourth and so on.. Is that intentional? It's returning inconsistent validations for some cards here compared with another algorithm I'm using. Try for example AmEx's 378282246310005.

How to properly create JQuery inArray if statement?

I am generating a list of random numbers. Each random number is added to an array, but I want to check that the same number isnt entered twice. I am having a lot of trouble trying to get the if statement to work with this and am not sure what I have done wrong.
I have created:
//INITIALISE VARS, ARRAYS
var uniquearr = [];
i = 0;
while (i < 30){
var min = 0;
var max = 29;
var random = Math.floor(Math.random() * (max - min + 1)) + min;
//SEARCH UNIQUE ARRAY FOR EXISTING
if (jQuery.inArray(random, uniquearr) > -1){
//ADD NUMBER TO UNIQUE ARRAY
uniquearr.push(random);
//*DO SOMETHING*
} //END IF
i++;
} //END WHILE
But the if statement never triggers. Can anyone point me in the right direction?
You need to test whether the random number does not exist in the array; only then should it be added to the array.
Also another problem with the logic was, you were not adding the 30 unique numbers always as the i variable was incremented outside the if condition. Here you do not have to use a different loop variable since you can check whether the destination array is of desired size
//INITIALISE VARS, ARRAYS
var uniquearr = [], min = 0, max = 29;
//SEARCH UNIQUE ARRAY FOR EXISTING
while (uniquearr.length < 30){
var random = Math.floor(Math.random() * (max - min + 1)) + min;
if (jQuery.inArray(random, uniquearr) == -1){
uniquearr.push(random);
}//END IF
}//END WHILE
console.log('uniquearr', uniquearr)
That's because your if statement always is false, your array is empty and as result $.inArray always returns -1, you should check whether the returned value is -1 or not.
while (uniquearr.length < 30) { // uniquearr.length !== 30
var min = 0,
max = 29,
random = Math.floor(Math.random() * (max - min + 1)) + min;
//SEARCH UNIQUE ARRAY FOR EXISTENCE
if (jQuery.inArray(random, uniquearr) === -1) {
//ADD NUMBER TO UNIQUE ARRAY
uniquearr.push(random);
}
}
http://jsfiddle.net/zzL7v/

javascript - generate a new random number

I have a variable that has a number between 1-3.
I need to randomly generate a new number between 1-3 but it must not be the same as the last one.
It happens in a loop hundreds of times.
What is the most efficient way of doing this?
May the powers of modular arithmetic help you!!
This function does what you want using the modulo operator:
/**
* generate(1) will produce 2 or 3 with probablity .5
* generate(2) will produce 1 or 3 with probablity .5
* ... you get the idea.
*/
function generate(nb) {
rnd = Math.round(Math.random())
return 1 + (nb + rnd) % 3
}
if you want to avoid a function call, you can inline the code.
Here is a jsFiddle that solves your problem : http://jsfiddle.net/AsMWG/
I've created an array containing 1,2,3 and first I select any number and swap it with the last element. Then I only pick elements from position 0 and 1, and swap them with last element.
var x = 1; // or 2 or 3
// this generates a new x out of [1,2,3] which is != x
x = (Math.floor(2*Math.random())+x) % 3 + 1;
You can randomly generate numbers with the random number generator built in to javascript. You need to use Math.random().
If you're push()-ing into an array, you can always check if the previously inserted one is the same number, thus you regenerate the number. Here is an example:
var randomArr = [];
var count = 100;
var max = 3;
var min = 1;
while (randomArr.length < count) {
var r = Math.floor(Math.random() * (max - min) + min);
if (randomArr.length == 0) {
// start condition
randomArr.push(r);
} else if (randomArr[randomArr.length-1] !== r) {
// if the previous value is not the same
// then push that value into the array
randomArr.push(r);
}
}
As Widor commented generating such a number is equivalent to generating a number with probability 0.5. So you can try something like this (not tested):
var x; /* your starting number: 1,2 or 3 */
var y = Math.round(Math.random()); /* generates 0 or 1 */
var i = 0;
var res = i+1;
while (i < y) {
res = i+1;
i++;
if (i+1 == x) i++;
}
The code is tested and it does for what you are after.
var RandomNumber = {
lastSelected: 0,
generate: function() {
var random = Math.floor(Math.random()*3)+1;
if(random == this.lastSelected) {
generateNumber();
}
else {
this.lastSelected = random;
return random;
}
}
}
RandomNumber.generate();

Categories

Resources