Generate Random Whole Number [duplicate] - javascript

This question already has answers here:
Generating random whole numbers in JavaScript in a specific range
(39 answers)
Closed 6 years ago.
I wan't to generate a random number and use it as a class name for an element.
Math.random();
This will generate a random number '0.7220265011042561'
Since this will be used as a class within the class attribute of an element, the decimal will surely cause problems and most likely isn't valid.
How can I generate a random whole number?

Math.round( Math.random()*10000000 )

This will generate a random whole number between 1 and 100.
Math.floor((Math.random() * 100) + 1);
Change the 100 part to redefine your range.

Add however many significant digits you want with the 100000 part:
Math.floor(Math.random() * 100000);
If you want them the same length, for smaller numbers (e.g., 5), here's a left-padded version:
var sigFig = // (put the number of significant digits you want here)
var number = Math.floor(Math.random() * Math.pow(10, sigFig));
var numStr = String(number);
while (numStr.length < sigFig) {
numStr = '0' + numStr;
}
// do stuff with numStr
Edit: Moved the significant figure to a variable.

Related

Random number generator doesn't produce expected numbers within a given range using values from input fields [duplicate]

This question already has answers here:
Generate random number between two numbers in JavaScript
(32 answers)
Closed 3 years ago.
I'm trying to generate a random number between two given values. I'm able to produce this with a pretty standard little function, however when I try to set the maximum and minimum values through an input field, I get some unexpected results.
This is using jQuery, which isn't necessary for this particular function but is needed for the larger project.
Here's an example of what I'm finding:
https://jsfiddle.net/u2k41hzd/
function randomNumber(min, max) {
points = Math.floor(Math.random() * (max - min + 1) + min);
}
$( "button" ).on( "click", function ( event ) {
minPoints = $( ".min-points" ).val();
maxPoints = $( ".max-points" ).val();
randomNumber(minPoints, maxPoints);
$(".random").html(points);
});
In the case of the minimum number being 1 and the maximum being 6, I would expect to get numbers between 1 and 6. However, I get numbers between 0 and 5.
If the minimum number is 2 and the maximum 6, I would expect to get numbers between 2 and 6, but get numbers between 0 and 4. Passing in 3 and 6 gives numbers between 0 and 3, and so on.
Ignoring the input values and hard coding them instead seems produce expected results with no issue. Essentially I'm just unsure as to why the input values are behaving as they are. I'm sure I've just misunderstood something or made a mistake somewhere, but I've not been able to determine the reason!
The issue is that you need to add the min to the rounded number, not to the randomly generated number:
function randomNumber(min, max) {
points = Math.floor(Math.random() * (max - min + 1)) + min;
}
To explain further, for the case of 2 and 9:
Math.random() generates a number between 0 and 0.999999999...
max - min + 1 = 8
So the generated number will be in the range 8 * 0 and 8 * 0.99999999...
Flooring it will round down in the range [0, 7]
The result would need to be offset by the starting number (i.e. the minimum allowed number - 2)

Creating random number on fractional part between two numbers

I am working on the following code. How can I create random number between 150.570 and 150.720?
As you can see the integer-part (150) is always fixed and I just need to get random on fractional-part (between .570 to .720) only.
var gapLeft = Math.floor(Math.random() * 150.720) + 150.570 ;
console.log(gapLeft);
Here is your solution for this,
console.log(150.57+Math.random()*(0.72-0.57));

How can I generate a random number between 1 and 2,147,483,647 [duplicate]

This question already has answers here:
Generating random whole numbers in JavaScript in a specific range
(39 answers)
Closed 6 years ago.
I know about random that generates a random number between 0 and 1.
Math.random();
But how can I generate a random number between 1 and 2,147,483,647 using Javascript?
You can simply multiply Math.random() times the limit value and then round down. Since Math.random() returns a decimal value between 0 and 1, you will always get some scaled proportion of your limit value so your result will be between 0 and your limit value.
If you want the result to be an integer, then use can call Math.floor() on the result of the multiplication to round down to an integer.
Since you also want the lowest value to be 1 instead of 0 and you want the result to include the limit value, then you can add 1 to the result to put it in the exact range.
var maxInt = 2147483647; // max 32-bit signed int
function randomInt() {
// generate random value between 1 and maxInt inclusive of both values
return Math.floor(Math.random() * maxInt) + 1;
}
Working demo: https://jsfiddle.net/jfriend00/ntkokacf/
In order to find a number you can do something to the effect of:
var randomNumber = Math.floor(Math.random() * 2147483647);
You can also write a function to repeat that and that will allow for any minimum or maximum:
function random(min, max) {
return min + Math.floor(Math.random() * (max - min + 1));
}
The explanation of the function is that it asks for a minimum and a maximum number. Whatever the minimum number is, we add to the second half of the return statement. The second half needs to give us the number of different possible numbers between min and max, so we multiply Math.random() by that exact number, which is the difference between max and min plus one. The problem is that this gives a decimal, therefore we take the floor of that to get rid of the decimal.

2 decimals in JavaScript with out regular expression and without rounding the numbers [duplicate]

This question already has answers here:
Format number to always show 2 decimal places
(37 answers)
How to round to at most 2 decimal places, if necessary
(91 answers)
Closed 8 years ago.
Can anyone give me the code for accepting only 2 decimals using JavaScript.
Without regular expression and without jQuery.
The number should not be round.
To Fixed
use toFixed(2); for doing that
var num = 2.4;
alert(num.toFixed(2)); will alert 2.40
Try with
parseFloat(Math.round(yourNum * 100) / 100).toFixed(2);
try this one
Math.round(num * 100) / 100
The number should not be round.
Use Math.floor to round down and you can use Math.pow to generically set the number of digits.
function trimDP(x, i) {
var e = Math.pow(10, i || 0);
return Math.floor(e * x) / e;
}
trimDP(2.45991, 2); // 2.45
If you want this as a String, you need to use .toFixed(i) after so that it doesn't get rounded.
var x = trimDP(2.40001, 2); // 2.4
x.toString(2); // "2.40"

How can I get a one-digit random number in JavaScript? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Generating random whole numbers in JavaScript in a specific range
How can I get one-digit random numbers (1, 2, 3, ..., not 0.1, 0.2, ... or 1.0, 5.0, ...) using Math.random() or some other way in JavaScript?
Math.random() returns a float between 0 and 1, so just multiply it by 10 and turn it into an integer:
Math.floor(Math.random() * 10)
Or something a little shorter:
~~(Math.random() * 10)
Disclaimer:
JavaScript's math.rand() is not cryptographically secure, meaning that this should not be used for password, PIN-code and/or gambling related random number generation. If this is your use case, please use the web crypto API instead! (W3C).
If the digit 0 is not included (1-9):
function randInt() {
return Math.floor((Math.random()*9) + 1);
}
If the digit 0 is included (0-9):
function randIntWithZero() {
return Math.floor((Math.random()*10));
}
var randomnumber=Math.floor(Math.random()*10)
where 10 dictates that the random number will fall between 0-9.
Math.floor((Math.random()*10));
And there goes your random integer between 0 and 10!
Use this:
Math.floor((Math.random()*9)+1);

Categories

Resources