Generate random number, between 2 numbers? [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Generating random numbers in Javascript in a specific range?
Say I wanted to generate a random number from 50 to 100.
I know there's:
Math.random()
but I could only find ways to go from 1 to 'x'

From MDN on Math.random():
// Returns a random integer between min and max
// Using Math.round() will give you a non-uniform distribution!
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}

I believe this would also work:
function randomInt(min,range) {
return Math.floor((Math.random()*(range+1))+min)
}
In your case min would be 50 and range would be 50

Related

Print a random integer number between 1 and 42 (both inclusive) to the console [duplicate]

This question already has answers here:
Generating random integer in range that doesn't start at zero
(4 answers)
Closed 3 days ago.
I have a question in a exercise to print a random integer number between 1 and 42, but im getting an error in my console "Are you doing the multiplication inside the ceil() method call?"
My code is this one.
var someRandomNumber = Math.random();
var wholeRandomNumber = Math.ceil(someRandomNumber);
console.log(Math.ceil(Math.random() * 42));
I dont know what im doing wrong, honestly if someone can help me! :)
You should try this
function generateRandom(min = 0, max = 1000) {
// find diff
let difference = max - min;
// generate random number
let rand = Math.random();
// multiply with difference
rand = Math.floor( rand * difference);
// add with min value
rand = rand + min;
return rand;
}
console.log(generateRandom(min=1,max=42));

Math random add subtract counter limited between a range of numbers [duplicate]

This question already has answers here:
Generating random whole numbers in JavaScript in a specific range
(40 answers)
Closed 2 years ago.
can you help me out on how to limit the below to stay within a min and max range eg 3 - 10
<div id="number">3</div>
setInterval(function(){
random = (Math.floor((Math.random()*1)+1));
var plusOrMinus = Math.random() < 0.5 ? -1 : 1;
random = random * plusOrMinus;
currentnumber = document.getElementById('number');
document.getElementById('number').innerHTML = parseInt(currentnumber.innerHTML) + random;
}, 1000);
See Mozilla Docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random#getting_a_random_number_between_two_values
Getting a random integer between two values This example returns a random integer between the specified values. The value is no lower
than min (or the next integer greater than min if min isn't an
integer), and is less than (but not equal to) max.
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
}
By Mozilla Contributors, licensed under CC-BY-SA 2.5.

Explanation of Code: Dealing with min and max - Javascript [duplicate]

This question already has answers here:
Generating random whole numbers in JavaScript in a specific range
(39 answers)
Closed 6 years ago.
function randomRange(myMin, myMax) {
return Math.floor(Math.random() * (myMax - myMin + 1)) +myMin;
}
I need a refresher on what the return statement is doing. I understand it creates a range for instance, 5 - 15. But I don't get why I'm subtracting the max from the min and adding + 1 and then +myMin.
But I don't get why im subtracting the max from the min and adding + 1 and then +myMin.
First remember that Math.random() returns a value in the range of [0, 1).
Lets start from the end:
+ myMin is done to ensure that the result is larger or equal to myMin.
Lets assume Math.random() returns 0. Then Math.floor(...) returns 0. If we didn't + myMin, return result would be 0 instead of myMin.
+ 1 is done to get random values that include myMax. Remember that Math.random() never returns 1, only values close to 1. I.e. the Math.floor(Math.random() * myMax) can never be myMax unless we add 1.
myMax - myMin is done because we do + myMin above. We have to account for increasing the result by myMin.
Lets assume Math.random() returns 0.5 and our range is 100 - 120. Without - myMin, we would get
Math.floor(0.5 * 120) + 100 = 60 + 100 = 160
That's clearly larger than 120. If we include - myMin:
Math.floor(0.5 * (120 - 100)) + 100 = (0.5 * 20) + 100 = 110
we get 110 which is exactly in the middle of our range (which makes sense intuitively since we get 0.5 as a random value).
Math.random returns float number between 0 to 1. For example if you take 1 to 10 range. Then Math.random will return minimum 0 and maximum 1 then you multiply it with 10-1=9. And you get 0 to 9. But when you add the minimum it will be increased to 1 to 10.
Correction - it's not creating a range, it is generating a random Integer number between a given range of numbers ( minimum and maximum number).
E.g. (5, 15) = (min, max)
Will result in a number that is in between this range.
Code explanation :
Math.floor(Math.random() * (myMax - myMin + 1)) +myMin;
Let's assume both max and min are = 15
So the above will look like:
Math.floor(Math.random() * (15 - 15 + 1)) + 15;
Which is equal to = 15, since 0 <= Math.random() * (1) < 1 so the floor of this is 0.
If you don't add that 1, it will not be valid for this corner case.
You add minimum to make sure the value remains between min and max.

How do I convert this simple python code into javascript? [duplicate]

This question already has answers here:
Generating random whole numbers in JavaScript in a specific range
(39 answers)
Closed 8 years ago.
I was looking at python script when I have across this:
randomNumber = random.randint(2, number)-1
How can I translate this into javascript?
Thanks?
You can use the examples given in the Math.random docs page,
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
console.log(getRandomInt(2, number) - 1);
randomNumber = Math.floor(Math.random() * (1 + number))

JavaScript math, round to two decimal places [duplicate]

This question already has answers here:
How to round to at most 2 decimal places, if necessary
(91 answers)
Closed 5 years ago.
I have the following JavaScript syntax:
var discount = Math.round(100 - (price / listprice) * 100);
This rounds up to the whole number. How can I return the result with two decimal places?
NOTE - See Edit 4 if 3 digit precision is important
var discount = (price / listprice).toFixed(2);
toFixed will round up or down for you depending on the values beyond 2 decimals.
Example: http://jsfiddle.net/calder12/tv9HY/
Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
Edit - As mentioned by others this converts the result to a string. To avoid this:
var discount = +((price / listprice).toFixed(2));
Edit 2- As also mentioned in the comments this function fails in some precision, in the case of 1.005 for example it will return 1.00 instead of 1.01. If accuracy to this degree is important I've found this answer: https://stackoverflow.com/a/32605063/1726511 Which seems to work well with all the tests I've tried.
There is one minor modification required though, the function in the answer linked above returns whole numbers when it rounds to one, so for example 99.004 will return 99 instead of 99.00 which isn't ideal for displaying prices.
Edit 3 - Seems having the toFixed on the actual return was STILL screwing up some numbers, this final edit appears to work. Geez so many reworks!
var discount = roundTo((price / listprice), 2);
function roundTo(n, digits) {
if (digits === undefined) {
digits = 0;
}
var multiplicator = Math.pow(10, digits);
n = parseFloat((n * multiplicator).toFixed(11));
var test =(Math.round(n) / multiplicator);
return +(test.toFixed(digits));
}
See Fiddle example here: https://jsfiddle.net/calder12/3Lbhfy5s/
Edit 4 - You guys are killing me. Edit 3 fails on negative numbers, without digging into why it's just easier to deal with turning a negative number positive before doing the rounding, then turning it back before returning the result.
function roundTo(n, digits) {
var negative = false;
if (digits === undefined) {
digits = 0;
}
if (n < 0) {
negative = true;
n = n * -1;
}
var multiplicator = Math.pow(10, digits);
n = parseFloat((n * multiplicator).toFixed(11));
n = (Math.round(n) / multiplicator).toFixed(digits);
if (negative) {
n = (n * -1).toFixed(digits);
}
return n;
}
Fiddle: https://jsfiddle.net/3Lbhfy5s/79/
If you use a unary plus to convert a string to a number as documented on MDN.
For example:+discount.toFixed(2)
The functions Math.round() and .toFixed() is meant to round to the nearest integer. You'll get incorrect results when dealing with decimals and using the "multiply and divide" method for Math.round() or parameter for .toFixed(). For example, if you try to round 1.005 using Math.round(1.005 * 100) / 100 then you'll get the result of 1, and 1.00 using .toFixed(2) instead of getting the correct answer of 1.01.
You can use following to solve this issue:
Number(Math.round(100 - (price / listprice) * 100 + 'e2') + 'e-2');
Add .toFixed(2) to get the two decimal places you wanted.
Number(Math.round(100 - (price / listprice) * 100 + 'e2') + 'e-2').toFixed(2);
You could make a function that will handle the rounding for you:
function round(value, decimals) {
return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}
Example:
https://jsfiddle.net/k5tpq3pd/36/
Alternative
You can add a round function to Number using prototype. I would not suggest adding .toFixed() here as it would return a string instead of number.
Number.prototype.round = function(decimals) {
return Number((Math.round(this + "e" + decimals) + "e-" + decimals));
}
and use it like this:
var numberToRound = 100 - (price / listprice) * 100;
numberToRound.round(2);
numberToRound.round(2).toFixed(2); //Converts it to string with two decimals
Example
https://jsfiddle.net/k5tpq3pd/35/
Source: http://www.jacklmoore.com/notes/rounding-in-javascript/
To get the result with two decimals, you can do like this :
var discount = Math.round((100 - (price / listprice) * 100) * 100) / 100;
The value to be rounded is multiplied by 100 to keep the first two digits, then we divide by 100 to get the actual result.
The best and simple solution I found is
function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
round(1.005, 2); // 1.01
try using discount.toFixed(2);
I think the best way I've seen it done is multiplying by 10 to the power of the number of digits, then doing a Math.round, then finally dividing by 10 to the power of digits. Here is a simple function I use in typescript:
function roundToXDigits(value: number, digits: number) {
value = value * Math.pow(10, digits);
value = Math.round(value);
value = value / Math.pow(10, digits);
return value;
}
Or plain javascript:
function roundToXDigits(value, digits) {
if(!digits){
digits = 2;
}
value = value * Math.pow(10, digits);
value = Math.round(value);
value = value / Math.pow(10, digits);
return value;
}
A small variation on the accepted answer.
toFixed(2) returns a string, and you will always get two decimal places. These might be zeros. If you would like to suppress final zero(s), simply do this:
var discount = + ((price / listprice).toFixed(2));
Edited:
I've just discovered what seems to be a bug in Firefox 35.0.1, which means that the above may give NaN with some values.
I've changed my code to
var discount = Math.round(price / listprice * 100) / 100;
This gives a number with up to two decimal places. If you wanted three, you would multiply and divide by 1000, and so on.
The OP wants two decimal places always, but if toFixed() is broken in Firefox it needs fixing first.
See https://bugzilla.mozilla.org/show_bug.cgi?id=1134388
Fastest Way - faster than toFixed():
TWO DECIMALS
x = .123456
result = Math.round(x * 100) / 100 // result .12
THREE DECIMALS
x = .123456
result = Math.round(x * 1000) / 1000 // result .123
function round(num,dec)
{
num = Math.round(num+'e'+dec)
return Number(num+'e-'+dec)
}
//Round to a decimal of your choosing:
round(1.3453,2)
Here is a working example
var value=200.2365455;
result=Math.round(value*100)/100 //result will be 200.24
To handle rounding to any number of decimal places, a function with 2 lines of code will suffice for most needs. Here's some sample code to play with.
var testNum = 134.9567654;
var decPl = 2;
var testRes = roundDec(testNum,decPl);
alert (testNum + ' rounded to ' + decPl + ' decimal places is ' + testRes);
function roundDec(nbr,dec_places){
var mult = Math.pow(10,dec_places);
return Math.round(nbr * mult) / mult;
}

Categories