This question already has answers here:
How to decide between two numbers randomly using javascript?
(4 answers)
Closed 1 year ago.
I've searched a lot for generating a random number but all I got is generating for a range between a or b.
I'm trying to get a number from a or b, i.e. either a or b, none from in between.
This returns the first value only
var number = 1 || 9; \\9
You can store your two numbers in an array and get a random index of that array. Here's an example:
var yourTwoNumbers = [2,5]
console.log(yourTwoNumbers[Math.floor(Math.random() * yourTwoNumbers.length)]);
So Math.random() randomly generates a number between 0.0 and 1.0. Math.random() < 0.5 has a 50% percent chance of either being true or false. This way you can select one of two numbers with equal probability.
let number = Math.random() < 0.5 ? 1 : 9;
console.log(number)
The same asked here: How to decide between two numbers randomly using javascript?
There is already an answer with explanations.
The Math.random[MDN] function chooses a random value in the interval [0, 1). You can take advantage of this to choose a value randomly.
const value1 = 1
const value2 = 9;
const chosenValue = Math.random() < 0.5 ? value1 : value2;
console.log(chosenValue)
This question already has answers here:
Generate random number between two numbers in JavaScript
(32 answers)
Closed 1 year ago.
this code is supposed to display a random character/ letter of a given name in javascript using while loops and if statements . . .
the problem that I faced is that the RandomLetterIndex is between 0 and 5 (<=5) when I want it to be between 0 and 4 (<5)
const MyName = "Ayman";
var RandomLetterIndex = Math.floor(Math.random() * 10);
while (RandomLetterIndex > MyName.length) {
RandomLetterIndex = Math.floor(Math.random() * 10);
if (RandomLetterIndex < MyName.length && RandomLetterIndex !== 5) {
break
}
}
console.log(RandomLetterIndex);
console.log(MyName.charAt(RandomLetterIndex));
If you want the random number to be less than the length of the word, instead of using while loops, you can do this
var RandomLetterIndex = Math.floor(Math.random()*MyName.length);
multiplying by length instead of 10 makes sure that the value always lies in the range [0, length-1] instead of [0, 10-1]
The problem is with the 0 based index and the length property. MyName.length will equate to 5 and thus the while loop will stop and the consoles print out.
while (RandomLetterIndex > MyName.length - 1) {
Try like this with the minus 1.
Your while loop ends when RandomLetterIndex is 5. Thats why you see a five in the console.
Also, you are breaking the loop, and therefore the while check is kind of useless.
This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 1 year ago.
Does anyone know why the exponent and round up functions aren't giving me the correct answers? I've gone through a load of debugging and I can't figure out what I'm doing that's making it's value abnormally large (like 25 orders larger)
function CAPEX(){
var initial = document.getElementById("CAPEX").value;
var lifespan = document.getElementById("life").value;
var interest = document.getElementById("IR").value;
var capitalrepayment = initial/lifespan;
var i;
var cap=0;
var expense =0;
for (i=0; i<lifespan;i++){
expense = capitalrepayment + (initial*interest);
cap = cap + expense;
initial = initial - capitalrepayment;
}
denominator = Math.pow((1+interest), lifespan);
console.log(denominator);
return cap;
}
I have a similar sort of issue here too where Math.ceil is returning a completely different answer too.
if(selected_scenario == "Divers"){
var totalTechnicians = numberNeeded * 3;
var supervisors = totalTechnicians/3;
var othertechnicians = totalTechnicians-supervisors;
var boats= Math.ceil((totalTechnicians+numberNeeded)/12);
divertotal = (numberNeeded*580)+(supervisors*516)+(othertechnicians*276)+(boats*2345)+9230+(boats*20);
}
For reference interest is 0.02, lifespan is 25, numberNeeded is 23. I'm reading these values in directly from a form number input.
The denominator should be 1.64 and boats should be 8.
The values that you are getting from the DOM are strings. You need to convert them to numbers before you can apply any mathematical operations to them. Try using parseInt() or parseFloat()
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
This question will need to be answered in Javascript.
For example, I have an array of phone numbers:
var phoneNumbers = ['123-434-4455', '123-495-8475', '484-728-3456'];
The phone number at index 0 (123-434-4455) would be added as 1+2+3+4+3+4+4+4+5+5, totaling to 35.
I'm guessing this will involve some kind of loop (for loops, or the method .forEach), because I will need to do this for multiple phone numbers in an array that will probably be randomly generated by a computer, so length and amount will vary.
Also, I'm wondering if the hyphen will matter, in which case I have found .replaceAll("-","");.
I've researched some other methods on here that involve .split, .parsInt, .map, .toString, .reduce, .digitSum, and more. They seem pretty complicated, especially since I'm in a beginning course (however I'm totally new to programming - this is my first post btw). Also, I'd rather not post the full question because I really want to figure it out alone, but this is the part I'm most stuck on. Forgive me if this has been answered previously! Like I said...new to programming.
I also need to determine which phone number has the last largest sum of digits, and use a return statement to return the required phone number in its’ original form.
You can use map and reduce array methods:
['123-434-4455', '123-495-8475', '484-728-3456'].map(function(str) {
return str.split('').reduce(function(a,b) {
return a + (+b || 0);
}, 0);
}); // [ 35, 48, 51 ]
Some notes:
split('') splits a string into an array of characters
+b coerces b into a number, e.g. "5" to 5 and "-" to NaN.
+b || 0 will return 0 if +b is falsy (0 or NaN), and +b otherwise
This code will do it:
var phoneNumbers = ["123-434-4455", "123-495-8475", "484-728-3456"];
for (var i=0; i<phoneNumbers.length; i++) {//For every phone number
var total=0; //create a total variable
var indNumbers = phoneNumbers[i].replace(/-/g, ""); //remove all dashes
for (var j=0; j<indNumbers.length; j++) {//loop for all digits
total+=parseFloat(indNumbers[j]);//add each digit to total
}
console.log(total);//do stuff with it here
}
All pretty standard javascript stuff. Only confusing bit I might have used is the .replace method - my parameter is /-/g which might look scary, but it's the equivalent of passing in "-" except it tells the function to replace ALL instances of the dash. If you do pass "-", it only replaces the first instance.
If you're a beginner, the things in this code you'll want to learn about are .replace, parseFloat for loops, and accessing strings using square bracket notation.
var phoneNumbers = ["123-434-4455", "123-495-8475", "484-728-3456"];
function crossSum(arr, pos) {
var sum = 0;
var a = arr[pos].split("-").join("").split("");
a.forEach(function(e, i) {
sum += parseInt(a[i]);
})
return sum;
}
document.write(crossSum(phoneNumbers, 0));
This function will return the cross-sum of
your phone-number.
Just use crossSum(phoneNumers, 0) // 0 is the fist number of phoneNumbers.
This will return the crossSum.
Adding on #millerbr answer. If you don't want to use .replace you can just use parseInt/parseFloat on every char, if it is not a number those functions returns NaN which can be checked with isNaN() function
var phoneNumbers = ["123-434-4455", "123-495-8475", "484-728-3456"];
for (var i=0; i < phoneNumbers.length; i++) { //For every phone number
var total=0; //create a total variable
for (var j=0; j < phoneNumbers.length; j++) { //loop for all digits
var parsedNumber = parseInt(phoneNumbers[j]); // parse string to number or NaN if "-"
if (!isNaN(parsedNumber)) { // Check if result is NaN (Not a Number).
total += parsedNumber; //add each digit to total
}
}
console.log(total);//do stuff with it here
}
Assuming that phoneNumbers is an array of strings, you can indeed loop through the entire array and then in each element in the array you can loop through the string and check if the character is a number. If so, add it to your sum and then when you finish each element in the array you have the total sum for it and you can add it to another array full of your sums.
This question already has answers here:
How do I check that a number is float or integer?
(52 answers)
Closed 7 years ago.
im trying to check if a number is a whole after a calculation. What I have so far prints out how many times one number gets divided by another, but when the number is not whole it dose not print anything out. Heres my code:
function round() {
var percent = document.getElementById('percent_sale').value;
var perShare = document.getElementById('singleShare').value;
var result = (percent / perShare);
if(result % 1 == 0) {
document.getElementById('results1').innerHTML = ('Number of shares:'+result);
} else {
document.getElementById(results1).innerHTML = ('number of shares must ');
}
}
The values get input buy a user, and the percent for sale is say 50 and the single share is say 2.5 this would return 20 shares.
What I need is if I put in something like 50 for sale and 3.15 single share it tells the user to make equal number of shares as it would return 15.87
Any ideas where ive gone wrong?
Convert your number into string and then check if the string contains only numbers
var num = 15;
var n = num.toString();
This will convert it into string then this
String.prototype.isNumber = function(){return /^\d+$/.test(this);}
console.log("123123".isNumber()); // outputs true
console.log("+12".isNumber()); // outputs false
For further reference.Link StackOverFlow