How to generate a random number from 2 numbers [duplicate] - javascript

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)

Related

the less than operator in javascript (<) is working as less or equals to [duplicate]

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.

Javascript Math.ceil and Math.pow returning wrong answer [duplicate]

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()

How to get the first two digits of a large float number in Javascript

I want to get the first two digits of a large float number e.g from 1115487.2644548 i want to get returned 11.154872644548.
Which Javascript native function to use to achieve such operation.
PS : toPrecision(2) isn't what i want.
Thanks.
Simple division
const num = 1115487.2644548;
console.log(num/100000);
console.log(parseInt(num/100000));
If the length of the integer is unknown, try this - other answers shows log versions
const num = 1115487.2644548;
const len = String(parseInt(num)).length
const two = len-2;
console.log(num/10**two); // without testing the len > 2
You could adjust by using the logarithm of ten.
function getTwo(v) {
return v / 10 ** (Math.floor(Math.log10(Math.floor(v))) - 1);
}
console.log(getTwo(1115487.2644548));
console.log(getTwo(111.54872644548));
console.log(getTwo(11154.872644548));
console.log(getTwo(99999));
console.log(getTwo(999.9999999999998863131622783839702606201171875));

JavaScript check if number is whole [duplicate]

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

Generate random number within range without repeating numbers in javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Generate 8 unique random numbers between 1 and 100
Generate unique number within range (0 - X), keeping a history to prevent duplicates
I need loop that will run 80 times and generate random number between 0-79 but it will not repeat number that has been generated already.
How can I do that?
for (var i = 0, ar = []; i < 80; i++) {
ar[i] = i;
}
// randomize the array
ar.sort(function () {
return Math.random() - 0.5;
});
// You have array ar with numbers 0 to 79 randomized. Verify
console.log(ar);
// take out elements like this
ar.pop()

Categories