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

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

Related

What will Math.floor(Math.random() * 10 + 1); do [duplicate]

This question already has answers here:
Generating random whole numbers in JavaScript in a specific range
(40 answers)
How does Math.floor(Math.random() * (Max - Min + 1) + Min) work in JavaScript? (Theory)
(3 answers)
Closed 8 months ago.
I came across the following command:
Math.floor(Math.random() * 10 + 1);
I understand that Math.floor() will convert to the lowest integer, but what does Math.random() * 10 + 1 do?
Math.random returns a floating point number x such that:
Multiplying 10 to x yields a floating point number in the range:
And then adding 1 to 10x yields a floating point number in the range:
And finally flooring 10x + 1 yields an integer in the range:
Therefore, Math.floor(Math.random() * 10 + 1) yields an integer that lies in the range [1, 10].
Math.random generates a random number between 0 and 1. So for example it can be .124 or .42242. When you multiply this random number against something, you are basically making it so that the new result is no less than 0, but no more than the number you are multiplying it against.
So in your example, you are multiplying it against 10, which means you will get a random number between 0 and 10 with decimals; technically this range is 'more than 0, but less than 10'. The +1 just increases the total range so that it is between 1 and 11, or 'more than 1, but less than 11.
When you apply Math.floor() to this, you are rounding all of these results down. So in the case without the '+1', your finite range is actually 0-9, and with the +1 it is 1-10

Generate Random Whole Number [duplicate]

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.

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"

Javascript (node.js) Math.floor returning long decimal values [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 9 years ago.
I can't seem to get a nice number rounded to the nearest hundredth (ie. 12.57 instead of 12.57000000008).
var example = {
user : "John",
dollars: 12.57
};
setInterval( function() {
example.dollars += (parseInt(Math.floor(Math.random()*2000 + 500)) / 100);
console.log(example.dollars);
}, 1000);
I keep getting values like:
15.20000000008
88.54000000007
86.36000000008
Am I setting something wrong in my Math function?
Note: This is in node.js
Javascript numbers are floating point numbers. They should not be relied upon for precision decimal operations.
For instance you can enter this into a js console
.1 + .2 //0.30000000000000004
Generally you can count on integer mathematics accurately,and if you need more control on decimal accuracy, you can look into libraries like this one which lets you set error bounds on your numbers, or make a call to an external library written in a language with better handling of number types.
More libraries for accurate JS decimal math:
https://npmjs.org/package/decimal
https://github.com/iriscouch/bigdecimal.js
Try isolating the number to the hundredth place. ie [86.36]000000008
var example = {
user : "John",
dollars: 12.57
};
setInterval(function() {
var s, final;
example.dollars += (parseInt(Math.floor(Math.random() * 2000 + 500)) / 100);
s = example.dollars + .005 + '',
final = s.substring(0, s.indexOf('.') + 3);
console.log(final);
}, 1000);
All we are doing is removing everything after the hundredth decimal place. in order to do that we need to find the decimal place so we can find the hundredth decimal value per say. First we must convert the number into a string, + '' or you can use the toString() function. then we use indexOf('.') to find the decimal placement and finally we count three places over. that will get you the number to the hundredth place, without the long decimal values.
Examples:
input: 12.57000000008 output: 12.57
input: 15.20000000008 output: 15.20
Working fiddle.
If you only need to support modern browsers, the toFixed method is the best choice. It takes an argument representing the number of decimal places to round to and returns a String.
example.dollars.toFixed(2); // returns "12.57"

Create a random number between -100 and 100 in JavaScript? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Generating random numbers in Javascript
I have the following code var randomnumber=Math.floor(Math.random()*101); that generates a random number for me between 1 and 100. What I would like to do is generate a random number between -100 and 100. I am not sure what to do exactly. Any help would be appreciated.
First, generate a random number between 1 - 200 then subtract 100:
var randomNumber = Math.floor(Math.random() * 201) - 100;
var randomnumber=Math.floor(Math.random()*200)-100;

Categories

Resources