How can I round down a number in Javascript? - javascript

How can I round down a number in JavaScript?
math.round() doesn't work because it rounds it to the nearest decimal.
I'm not sure if there is a better way of doing it other than breaking it apart at the decimal point at keeping the first bit. There must be...

Using Math.floor() is one way of doing this.
More information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor

Round towards negative infinity - Math.floor()
+3.5 => +3.0
-3.5 => -4.0
Round towards zero can be done using Math.trunc(). Older browsers do not support this function. If you need to support these, you can use Math.ceil() for negative numbers and Math.floor() for positive numbers.
+3.5 => +3.0 using Math.floor()
-3.5 => -3.0 using Math.ceil()

Math.floor() will work, but it's very slow compared to using a bitwise OR operation:
var rounded = 34.923 | 0;
alert( rounded );
//alerts "34"
EDIT Math.floor() is not slower than using the | operator. Thanks to Jason S for checking my work.
Here's the code I used to test:
var a = [];
var time = new Date().getTime();
for( i = 0; i < 100000; i++ ) {
//a.push( Math.random() * 100000 | 0 );
a.push( Math.floor( Math.random() * 100000 ) );
}
var elapsed = new Date().getTime() - time;
alert( "elapsed time: " + elapsed );

You can try to use this function if you need to round down to a specific number of decimal places
function roundDown(number, decimals) {
decimals = decimals || 0;
return ( Math.floor( number * Math.pow(10, decimals) ) / Math.pow(10, decimals) );
}
examples
alert(roundDown(999.999999)); // 999
alert(roundDown(999.999999, 3)); // 999.999
alert(roundDown(999.999999, -1)); // 990

Rounding a number towards 0 (aka "truncating its fractional part") can be done by subtracting its signed fractional part number % 1:
rounded = number - number % 1;
Like Math.floor (rounds towards -Infinity) this method is perfectly accurate.
There are differences in the handling of -0, +Infinity and -Infinity though:
Math.floor(-0) => -0
-0 - -0 % 1 => +0
Math.floor(Infinity) => Infinity
Infinity - Infinity % 1 => NaN
Math.floor(-Infinity) => -Infinity
-Infinity - -Infinity % 1 => NaN

Math.floor(1+7/8)

To round down towards negative infinity, use:
rounded=Math.floor(number);
To round down towards zero (if the number can round to a 32-bit integer between -2147483648 and 2147483647), use:
rounded=number|0;
To round down towards zero (for any number), use:
if(number>0)rounded=Math.floor(number);else rounded=Math.ceil(number);

Was fiddling round with someone elses code today and found the following which seems rounds down as well:
var dec = 12.3453465,
int = dec >> 0; // returns 12
For more info on the Sign-propagating right shift(>>) see MDN Bitwise Operators
It took me a while to work out what this was doing :D
But as highlighted above, Math.floor() works and looks more readable in my opinion.

This was the best solution I found that works reliably.
function round(value, decimals) {
return Number(Math.floor(parseFloat(value + 'e' + decimals)) + 'e-' + decimals);
}
Credit to: Jack L Moore's blog

You need to put -1 to round half down and after that multiply by -1 like the example down bellow.
<script type="text/javascript">
function roundNumber(number, precision, isDown) {
var factor = Math.pow(10, precision);
var tempNumber = number * factor;
var roundedTempNumber = 0;
if (isDown) {
tempNumber = -tempNumber;
roundedTempNumber = Math.round(tempNumber) * -1;
} else {
roundedTempNumber = Math.round(tempNumber);
}
return roundedTempNumber / factor;
}
</script>
<div class="col-sm-12">
<p>Round number 1.25 down: <script>document.write(roundNumber(1.25, 1, true));</script>
</p>
<p>Round number 1.25 up: <script>document.write(roundNumber(1.25, 1, false));</script></p>
</div>

Here is math.floor being used in a simple example. This might help a new developer to get an idea how to use it in a function and what it does. Hope it helps!
<script>
var marks = 0;
function getRandomNumbers(){ // generate a random number between 1 & 10
var number = Math.floor((Math.random() * 10) + 1);
return number;
}
function getNew(){
/*
This function can create a new problem by generating two random numbers. When the page is loading as the first time, this function is executed with the onload event and the onclick event of "new" button.
*/
document.getElementById("ans").focus();
var num1 = getRandomNumbers();
var num2 = getRandomNumbers();
document.getElementById("num1").value = num1;
document.getElementById("num2").value = num2;
document.getElementById("ans").value ="";
document.getElementById("resultBox").style.backgroundColor = "maroon"
document.getElementById("resultBox").innerHTML = "***"
}
function checkAns(){
/*
After entering the answer, the entered answer will be compared with the correct answer.
If the answer is correct, the text of the result box should be "Correct" with a green background and 10 marks should be added to the total marks.
If the answer is incorrect, the text of the result box should be "Incorrect" with a red background and 3 marks should be deducted from the total.
The updated total marks should be always displayed at the total marks box.
*/
var num1 = eval(document.getElementById("num1").value);
var num2 = eval(document.getElementById("num2").value);
var answer = eval(document.getElementById("ans").value);
if(answer==(num1+num2)){
marks = marks + 10;
document.getElementById("resultBox").innerHTML = "Correct";
document.getElementById("resultBox").style.backgroundColor = "green";
document.getElementById("totalMarks").innerHTML= "Total marks : " + marks;
}
else{
marks = marks - 3;
document.getElementById("resultBox").innerHTML = "Wrong";
document.getElementById("resultBox").style.backgroundColor = "red";
document.getElementById("totalMarks").innerHTML = "Total Marks: " + marks ;
}
}
</script>
</head>
<body onLoad="getNew()">
<div class="container">
<h1>Let's add numbers</h1>
<div class="sum">
<input id="num1" type="text" readonly> + <input id="num2" type="text" readonly>
</div>
<h2>Enter the answer below and click 'Check'</h2>
<div class="answer">
<input id="ans" type="text" value="">
</div>
<input id="btnchk" onClick="checkAns()" type="button" value="Check" >
<div id="resultBox">***</div>
<input id="btnnew" onClick="getNew()" type="button" value="New">
<div id="totalMarks">Total marks : 0</div>
</div>
</body>
</html>

Math.round(3.14159 * 100) / 100 // 3.14
3.14159.toFixed(2); // 3.14 returns a string
parseFloat(3.14159.toFixed(2)); // 3.14 returns a number
Math.round(3.14159) // 3
Math.round(3.5) // 4
Math.floor(3.8) // 3
Math.ceil(3.2) // 4

Related

How to format numbers as percentage values in JavaScript?

Was using ExtJS for formatting numbers to percentage earlier. Now as we are not using ExtJS anymore same has to be accomplished using normal JavaScript.
Need a method that will take number and format (usually in %) and convert that number to that format.
0 -> 0.00% = 0.00%
25 -> 0.00% = 25.00%
50 -> 0.00% = 50.00%
150 -> 0.00% = 150.00%
You can use Number.toLocaleString():
var num=25;
var s = Number(num/100).toLocaleString(undefined,{style: 'percent', minimumFractionDigits:2});
console.log(s);
No '%' sign needed, output is:
25.00%
See documentation for toLocaleString() for more options for the format object parameter.
Here is what you need.
var x=150;
console.log(parseFloat(x).toFixed(2)+"%");
x=0;
console.log(parseFloat(x).toFixed(2)+"%");
x=10
console.log(parseFloat(x).toFixed(2)+"%");
Modern JS:
For any of these, remove * 100 if you start with a whole number instead of decimal.
Basic
const displayPercent = (percent) => `${(percent * 100).toFixed(2)}%`;
Dynamic with safe handling for undefined values
const displayPercent = (percent, fallback, digits = 2) =>
(percent === null || percent === undefined) ? fallback : `${(percent * 100).toFixed(digits)}%`;
Typescript:
const displayPercent = (percent: number) => `${(percent * 100).toFixed(2)}%`;
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
function myFunction(num) {
number = num.toString();;
console.log(number)
var words2 = number.split(".");
for (var i = 0; i < words2.length; i++) {
words2[i] += " ";
}
num1 = words2[0];
num2 = words2[1];
num1 = num1.trim();
if(num2==undefined){
number1 = num1+'.00%';
return number1;
}else{
num2 = num2.trim();
number1 = num1+'.'+num2+'%';
return number1;
}
}
document.getElementById("demo").innerHTML = myFunction(50.12);
</script>
</body>
</html>
I had decimal values such as 0.01235 and 0.016858542 that I wanted to convert to percentages 1.235% and 1.6858542% respectively. I thought it was going to be easy, just calculate (0.012858542 * 100) and I'm good to go. I was wrong, (0.012858542 * 100) = 1.2858542000000002 because of decimal conversion.
Let's add toFixed() to the calculation and I end up with the right value.
(0.012858542*100).toFixed(7) // returns "1.2858542"
(0.01235*100).toFixed(7) // returns "1.2350000"
I don't like to show four trailing zeros when they're unnecessary. One solution I thought about was to use replace() to remove all trailing zeros but I ended up using Numeral.js instead because it does all the work for me while it's lightweight. I can recommend it!
import numeral from 'numeral';
numeral(0.012858542 * 100).format('0.00[0000]') // returns "1.2858542"
numeral(0.01235 * 100).format('0.00[0000]') // returns "1.235"
Transform number to percentage with X float decimal positions
function toPercent(number, float) {
var percent = parseFloat(number * 100).toFixed(float) + "%";
return percent;
}

How to Generate a random number of fixed length using JavaScript?

I'm trying to generate a random number that must have a fixed length of exactly 6 digits.
I don't know if JavaScript has given below would ever create a number less than 6 digits?
Math.floor((Math.random()*1000000)+1);
I found this question and answer on StackOverflow here. But, it's unclear.
EDIT: I ran the above code a bunch of times, and Yes, it frequently creates numbers less than 6 digits. Is there a quick/fast way to make sure it's always exactly 6 digits?
console.log(Math.floor(100000 + Math.random() * 900000));
Will always create a number of 6 digits and it ensures the first digit will never be 0. The code in your question will create a number of less than 6 digits.
Only fully reliable answer that offers full randomness, without loss. The other ones prior to this answer all looses out depending on how many characters you want. The more you want, the more they lose randomness.
They achieve it by limiting the amount of numbers possible preceding the fixed length.
So for instance, a random number of fixed length 2 would be 10 - 99. For 3, 100 - 999. For 4, 1000 - 9999. For 5 10000 - 99999 and so on. As can be seen by the pattern, it suggests 10% loss of randomness because numbers prior to that are not possible. Why?
For really large numbers ( 18, 24, 48 ) 10% is still a lot of numbers to loose out on.
function generate(n) {
var add = 1, max = 12 - add; // 12 is the min safe number Math.random() can generate without it starting to pad the end with zeros.
if ( n > max ) {
return generate(max) + generate(n - max);
}
max = Math.pow(10, n+add);
var min = max/10; // Math.pow(10, n) basically
var number = Math.floor( Math.random() * (max - min + 1) ) + min;
return ("" + number).substring(add);
}
The generator allows for ~infinite length without lossy precision and with minimal performance cost.
Example:
generate(2)
"03"
generate(2)
"72"
generate(2)
"20"
generate(3)
"301"
generate(3)
"436"
generate(3)
"015"
As you can see, even the zero are included initially which is an additional 10% loss just that, besides the fact that numbers prior to 10^n are not possible.
That is now a total of 20%.
Also, the other options have an upper limit on how many characters you can actually generate.
Example with cost:
var start = new Date(); var num = generate(1000); console.log('Time: ', new Date() - start, 'ms for', num)
Logs:
Time: 0 ms for 7884381040581542028523049580942716270617684062141718855897876833390671831652069714762698108211737288889182869856548142946579393971303478191296939612816492205372814129483213770914444439430297923875275475120712223308258993696422444618241506074080831777597175223850085606310877065533844577763231043780302367695330451000357920496047212646138908106805663879875404784849990477942580056343258756712280958474020627842245866908290819748829427029211991533809630060693336825924167793796369987750553539230834216505824880709596544701685608502486365633618424746636614437646240783649056696052311741095247677377387232206206230001648953246132624571185908487227730250573902216708727944082363775298758556612347564746106354407311558683595834088577220946790036272364740219788470832285646664462382109714500242379237782088931632873392735450875490295512846026376692233811845787949465417190308589695423418373731970944293954443996348633968914665773009376928939207861596826457540403314327582156399232931348229798533882278769760
More hardcore:
generate(100000).length === 100000 -> true
I would go with this solution:
Math.floor(Math.random() * 899999 + 100000)
More generally, generating a random integer with fixed length can be done using Math.pow:
var randomFixedInteger = function (length) {
return Math.floor(Math.pow(10, length-1) + Math.random() * (Math.pow(10, length) - Math.pow(10, length-1) - 1));
}
To answer the question: randomFixedInteger(6);
You can use the below code to generate a random number that will always be 6 digits:
Math.random().toString().substr(2, 6)
Hope this works for everyone :)
Briefly how this works is Math.random() generates a random number between 0 and 1 which we convert to a string and using .toString() and take a 6 digit sample from said string using .substr() with the parameters 2, 6 to start the sample from the 2nd char and continue it for 6 characters.
This can be used for any length number.
If you want to do more reading on this here are some links to the docs to save you some googling:
Math.random(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random
.toString(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
.substr(): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr
short with arbitrary precision
below code ALWAYS generate string with n digits - solution in snippet use it
[...Array(n)].map(_=>Math.random()*10|0).join``
let gen = n=> [...Array(n)].map(_=>Math.random()*10|0).join``
// TEST: generate 6 digit number
// first number can't be zero - so we generate it separatley
let sixDigitStr = (1+Math.random()*9|0) + gen(5)
console.log( +(sixDigitStr) ) // + convert to num
100000 + Math.floor(Math.random() * 900000);
will give a number from 100000 to 999999 (inclusive).
Based on link you've provided, right answer should be
Math.floor(Math.random()*899999+100000);
Math.random() returns float between 0 and 1, so minimum number will be 100000, max - 999999. Exactly 6 digits, as you wanted :)
Here is my function I use. n - string length you want to generate
function generateRandomNumber(n) {
return Math.floor(Math.random() * (9 * Math.pow(10, n - 1))) + Math.pow(10, n - 1);
}
This is another random number generator that i use often, it also prevent the first digit from been zero(0)
function randomNumber(length) {
var text = "";
var possible = "123456789";
for (var i = 0; i < length; i++) {
var sup = Math.floor(Math.random() * possible.length);
text += i > 0 && sup == i ? "0" : possible.charAt(sup);
}
return Number(text);
}
let length = 6;
("0".repeat(length) + Math.floor(Math.random() * 10 ** length)).slice(-length);
Math.random() - Returns floating point number between 0 - 1
10 ** length - Multiply it by the length so we can get 1 - 6 length numbers with decimals
Math.floor() - Returns above number to integer(Largest integer to the given number).
What if we get less than 6 digits number?
That's why you have to append 0s with it.
"0".repeat() repeats the given string which is 0
So we may get more than 6 digits right?
That's why we have to use "".slice() method. It returns the array within given indexes. By giving minus values, it counts from the last element.
I created the below function to generate random number of fix length:
function getRandomNum(length) {
var randomNum =
(Math.pow(10,length).toString().slice(length-1) +
Math.floor((Math.random()*Math.pow(10,length))+1).toString()).slice(-length);
return randomNum;
}
This will basically add 0's at the beginning to make the length of the number as required.
npm install --save randomatic
var randomize = require('randomatic');
randomize(pattern, length, options);
Example:
To generate a 10-character randomized string using all available characters:
randomize('*', 10);
//=> 'x2_^-5_T[$'
randomize('Aa0!', 10);
//=> 'LV3u~BSGhw'
a: Lowercase alpha characters (abcdefghijklmnopqrstuvwxyz'
A: Uppercase alpha characters (ABCDEFGHIJKLMNOPQRSTUVWXYZ')
0: Numeric characters (0123456789')
!: Special characters (~!##$%^&()_+-={}[];\',.)
*: All characters (all of the above combined)
?: Custom characters (pass a string of custom characters to the options)
NPM repo
I use randojs to make the randomness simpler and more readable. you can pick a random int between 100000 and 999999 like this with randojs:
console.log(rando(100000, 999999));
<script src="https://randojs.com/1.0.0.js"></script>
const generate = n => String(Math.ceil(Math.random() * 10**n)).padStart(n, '0')
// n being the length of the random number.
Use a parseInt() or Number() on the result if you want an integer.
If you don't want the first integer to be a 0 then you could use padEnd() instead of padStart().
I was thinking about the same today and then go with the solution.
var generateOTP = function(otpLength=6) {
let baseNumber = Math.pow(10, otpLength -1 );
let number = Math.floor(Math.random()*baseNumber);
/*
Check if number have 0 as first digit
*/
if (number < baseNumber) {
number += baseNumber;
}
return number;
};
Let me know if it has any bug. Thanks.
"To Generate Random Number Using JS"
console.log(
Math.floor(Math.random() * 1000000)
);
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.random()</h2>
<p id="demo"></p>
</body>
</html>
You can use this module https://www.npmjs.com/package/uid, it generates variable length unique id
uid(10) => "hbswt489ts"
uid() => "rhvtfnt" Defaults to 7
Or you can have a look at this module https://www.npmjs.com/package/shortid
const shortid = require('shortid');
console.log(shortid.generate());
// PPBqWA9
Hope it works for you :)
var number = Math.floor(Math.random() * 9000000000) + 1000000000;
console.log(number);
This can be simplest way and reliable one.
For the length of 6, recursiveness doesn't matter a lot.
function random(len) {
let result = Math.floor(Math.random() * Math.pow(10, len));
return (result.toString().length < len) ? random(len) : result;
}
console.log(random(6));
In case you also want the first digit to be able to be 0 this is my solution:
const getRange = (size, start = 0) => Array(size).fill(0).map((_, i) => i + start);
const getRandomDigit = () => Math.floor(Math.random() * 10);
const generateVerificationCode = () => getRange(6).map(getRandomDigit).join('');
console.log(generateVerificationCode())
generate a random number that must have a fixed length of exactly 6 digits:
("000000"+Math.floor((Math.random()*1000000)+1)).slice(-6)
Generate a random number that will be 6 digits:
console.log(Math.floor(Math.random() * 900000));
Result = 500229
Generate a random number that will be 4 digits:
console.log(Math.floor(Math.random() * 9000));
Result = 8751
This code provides nearly full randomness:
function generator() {
const ran = () => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0].sort((x, z) => {
ren = Math.random();
if (ren == 0.5) return 0;
return ren > 0.5 ? 1 : -1
})
return Array(6).fill(null).map(x => ran()[(Math.random() * 9).toFixed()]).join('')
}
console.log(generator())
This code provides complete randomness:
function generator() {
const ran1 = () => [1, 2, 3, 4, 5, 6, 7, 8, 9, 0].sort((x, z) => {
ren = Math.random();
if (ren == 0.5) return 0;
return ren > 0.5 ? 1 : -1
})
const ran2 = () => ran1().sort((x, z) => {
ren = Math.random();
if (ren == 0.5) return 0;
return ren > 0.5 ? 1 : -1
})
return Array(6).fill(null).map(x => ran2()[(Math.random() * 9).toFixed()]).join('')
}
console.log(generator())
parseInt(Math.random().toString().slice(2,Math.min(length+2, 18)), 10); // 18 -> due to max digits in Math.random
Update:
This method has few flaws:
- Sometimes the number of digits might be lesser if its left padded with zeroes.

Rounding up to the nearest 0.05 in JavaScript

Question
Does anyone know of a way to round a float to the nearest 0.05 in JavaScript?
Example
BEFORE | AFTER
2.51 | 2.55
2.50 | 2.50
2.56 | 2.60
Current Code
var _ceil = Math.ceil;
Math.ceil = function(number, decimals){
if (arguments.length == 1)
return _ceil(number);
multiplier = Math.pow(10, decimals);
return _ceil(number * multiplier) / multiplier;
}
Then elsewhere...
return (Math.ceil((amount - 0.05), 1) + 0.05).toFixed(2);
Which is resulting in...
BEFORE | AFTER
2.51 | 2.55
2.50 | 2.55
2.56 | 2.65
Multiply by 20, then divide by 20:
(Math.ceil(number*20)/20).toFixed(2)
Rob's answer with my addition:
(Math.ceil(number*20 - 0.5)/20).toFixed(2)
Otherwise it always rounds up to the nearest 0.05.
** UPDATE **
Sorry has been pointed out this is not what the orig poster wanted.
I would go for the standard of actually dividing by the number you're factoring it to, and rounding that and multiplying it back again after. That seems to be a proper working method which you can use with any number and maintain the mental image of what you are trying to achieve.
var val = 26.14,
factor = 0.05;
val = Math.round(val / factor) * factor;
This will work for tens, hundreds or any number. If you are specifically rounding to the higher number then use Math.ceil instead of Math.round.
Another method specifically for rounding just to 1 or more decimal places (rather than half a place) is the following:
Number(Number(1.5454545).toFixed(1));
It creates a fixed number string and then turns it into a real Number.
I would write a function that does it for you by
move the decimal over two places (multiply by 100)
then mod (%) that inflatedNumber by 5 and get the remainder
subtract the remainder from 5 so that you know what the 'gap'(ceilGap) is between your number and the next closest .05
finally, divide your inflatedNumber by 100 so that it goes back to your original float, and voila, your num will be rounded up to the nearest .05.
function calcNearestPointZeroFive(num){
var inflatedNumber = num*100,
remainder = inflatedNumber % 5;
ceilGap = 5 - remainder
return (inflatedNumber + ceilGap)/100
}
If you want to leave numbers like 5.50 untouched you can always add this checker:
if (remainder===0){
return num
} else {
var ceilGap = 5 - remainder
return (inflatedNumber + ceilGap)/100
}
You need to put -1 to round half down and after that multiply by -1 like the example down bellow.
<script type="text/javascript">
function roundNumber(number, precision, isDown) {
var factor = Math.pow(10, precision);
var tempNumber = number * factor;
var roundedTempNumber = 0;
if (isDown) {
tempNumber = -tempNumber;
roundedTempNumber = Math.round(tempNumber) * -1;
} else {
roundedTempNumber = Math.round(tempNumber);
}
return roundedTempNumber / factor;
}
</script>
<div class="col-sm-12">
<p>Round number 1.25 down: <script>document.write(roundNumber(1.25, 1, true));</script>
</p>
<p>Round number 1.25 up: <script>document.write(roundNumber(1.25, 1, false));</script></p>
</div>
I ended up using this function in my project, successfully:
roundToNearestFiveCents( number: any ) {
return parseFloat((Math.round(number / 0.05) * 0.05).toFixed(2));
}
Might be of use to someone wanting to simply round to the nearest 5 cents on their monetary results, keeps the result a number, so if you perform addition on it further it won't result in string concatenation; also doesn't unnecessarily round up as a few of the other answers pointed out. Also limits it to two decimals, which is customary with finance.
My solution and test:
let round = function(number, precision = 2, rounding = 0.05) {
let multiply = 1 / rounding;
return parseFloat((Math.round(number * multiply) / multiply)).toFixed(precision);
};
https://jsfiddle.net/maciejSzewczyk/7r1tvhdk/40/
Even though the OP is not explicit about banker rounding, rounding up to the nearest $0.05 (5 cents) should be compatible with banker rounding. What suggested by Arth is more accurate than the accepted answer by Rob W.
(Math.ceil(number*20 - 0.5)/20).toFixed(2)
With banker rounding, you need a basic banker rounding function as suggested at Gaussian/banker's rounding in JavaScript, and I rewrite in TypeScript:
static bankerRound(num: number, decimalPlaces?: number) {
const d = decimalPlaces || 0;
const m = Math.pow(10, d);
const n = +(d ? num * m : num).toFixed(8);
const i = Math.floor(n), f = n - i;
const e = 1e-8;
const r = (f > 0.5 - e && f < 0.5 + e) ?
((i % 2 === 0) ? i : i + 1) : Math.round(n);
return d ? r / m : r;
}
static roundTo5cents(num: number) {
const r = bankerRound(Math.ceil(num * 20 - 0.5) / 20, 2);
return r;
}
The correctness of this algorithm could be verified through MBS Online, e.g. http://www9.health.gov.au/mbs/ready_reckoner.cfm?item_num=60

JavaScript, Generate a Random Number that is 9 numbers in length

I'm looking for an efficient, elegant way to generate a JavaScript variable that is 9 digits in length:
Example: 323760488
You could generate 9 random digits and concatenate them all together.
Or, you could call random() and multiply the result by 1000000000:
Math.floor(Math.random() * 1000000000);
Since Math.random() generates a random double precision number between 0 and 1, you will have enough digits of precision to still have randomness in your least significant place.
If you want to ensure that your number starts with a nonzero digit, try:
Math.floor(100000000 + Math.random() * 900000000);
Or pad with zeros:
function LeftPadWithZeros(number, length)
{
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
Or pad using this inline 'trick'.
why don't just extract digits from the Math.random() string representation?
Math.random().toString().slice(2,11);
/*
Math.random() -> 0.12345678901234
.toString() -> "0.12345678901234"
.slice(2,11) -> "123456789"
*/
(requirement is that every javascript implementation Math.random()'s precision is at least 9 decimal places)
Also...
function getRandom(length) {
return Math.floor(Math.pow(10, length-1) + Math.random() * 9 * Math.pow(10, length-1));
}
getRandom(9) => 234664534
Three methods I've found in order of efficiency:
(Test machine running Firefox 7.0 Win XP)
parseInt(Math.random()*1000000000, 10)
1 million iterations: ~626ms. By far the fastest - parseInt is a native function vs calling the Math library again. NOTE: See below.
Math.floor(Math.random()*1000000000)
1 million iterations: ~1005ms. Two function calls.
String(Math.random()).substring(2,11)
1 million iterations: ~2997ms. Three function calls.
And also...
parseInt(Math.random()*1000000000)
1 million iterations: ~362ms.
NOTE: parseInt is usually noted as unsafe to use without radix parameter. See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt or google "JavaScript: The Good Parts". However, it seems the parameter passed to parseInt will never begin with '0' or '0x' since the input is first multiplied by 1000000000. YMMV.
Math.random().toFixed(length).split('.')[1]
Using toFixed alows you to set the length longer than the default (seems to generate 15-16 digits after the decimal. ToFixed will let you get more digits if you need them.
In one line(ish):
var len = 10;
parseInt((Math.random() * 9 + 1) * Math.pow(10,len-1), 10);
Steps:
We generate a random number that fulfil 1 ≤ x < 10.
Then, we multiply by Math.pow(10,len-1) (number with a length len).
Finally, parseInt() to remove decimals.
Thought I would take a stab at your question. When I ran the following code it worked for me.
<script type="text/javascript">
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
} //The maximum is exclusive and the minimum is inclusive
$(document).ready(function() {
$("#random-button").on("click", function() {
var randomNumber = getRandomInt(100000000, 999999999);
$("#random-number").html(randomNumber);
});
</script>
Does this already have enough answers?
I guess not. So, this should reliably provide a number with 9 digits, even if Math.random() decides to return something like 0.000235436:
Math.floor((Math.random() + Math.floor(Math.random()*9)+1) * Math.pow(10, 8))
Screen scrape this page:
9 random numbers
function rand(len){var x='';
for(var i=0;i<len;i++){x+=Math.floor(Math.random() * 10);}
return x;
}
rand(9);
If you mean to generate random telephone number, then they usually are forbidden to start with zero.
That is why you should combine few methods:
Math.floor(Math.random()*8+1)+Math.random().toString().slice(2,10);
this will generate random in between 100 000 000 to 999 999 999
With other methods I had a little trouble to get reliable results as leading zeroes was somehow a problem.
I know the answer is old, but I want to share this way to generate integers or float numbers from 0 to n. Note that the position of the point (float case) is random between the boundaries. The number is an string because the limitation of the MAX_SAFE_INTEGER that is now 9007199254740991
Math.hRandom = function(positions, float = false) {
var number = "";
var point = -1;
if (float) point = Math.floor(Math.random() * positions) + 1;
for (let i = 0; i < positions; i++) {
if (i == point) number += ".";
number += Math.floor(Math.random() * 10);
}
return number;
}
//integer random number 9 numbers
console.log(Math.hRandom(9));
//float random number from 0 to 9e1000 with 1000 numbers.
console.log(Math.hRandom(1000, true));
function randomCod(){
let code = "";
let chars = 'abcdefghijlmnopqrstuvxwz';
let numbers = '0123456789';
let specialCaracter = '/{}$%&#*/()!-=?<>';
for(let i = 4; i > 1; i--){
let random = Math.floor(Math.random() * 99999).toString();
code += specialCaracter[random.substring(i, i-1)] + ((parseInt(random.substring(i, i-1)) % 2 == 0) ? (chars[random.substring(i, i-1)].toUpperCase()) : (chars[random.substring(i, i+1)])) + (numbers[random.substring(i, i-1)]);
}
code = (code.indexOf("undefined") > -1 || code.indexOf("NaN") > -1) ? randomCod() : code;
return code;
}
With max exclusive: Math.floor(Math.random() * max);
With max inclusive: Math.round(Math.random() * max);
To generate a number string with length n, thanks to #nvitaterna, I came up with this:
1 + Math.floor(Math.random() * 9) + Math.random().toFixed(n - 1).split('.')[1]
It prevents first digit to be zero.
It can generate string with length ~ 50 each time you call it.
var number = Math.floor(Math.random() * 900000000) + 100000000
var number = Math.floor(Math.random()*899999999 + 100000000)
For a number of 10 characters
Math.floor(Math.random() * 9000000000) + 1000000000
From https://gist.github.com/lpf23/9762508
This answer is intended for people who are looking to generate a 10 digit number (without a country code)

Round number up to the nearest multiple of 3

How would I go about rounded a number up the nearest multiple of 3?
i.e.
25 would return 27
1 would return 3
0 would return 3
6 would return 6
if(n > 0)
return Math.ceil(n/3.0) * 3;
else if( n < 0)
return Math.floor(n/3.0) * 3;
else
return 3;
Simply:
3.0*Math.ceil(n/3.0)
?
Here you are!
Number.prototype.roundTo = function(num) {
var resto = this%num;
if (resto <= (num/2)) {
return this-resto;
} else {
return this+num-resto;
}
}
Examples:
y = 236.32;
x = y.roundTo(10);
// results in x = 240
y = 236.32;
x = y.roundTo(5);
// results in x = 235
I'm answering this in psuedocode since I program mainly in SystemVerilog and Vera (ASIC HDL). % represents a modulus function.
round_number_up_to_nearest_divisor = number + ((divisor - (number % divisor)) % divisor)
This works in any case.
The modulus of the number calculates the remainder, subtracting that from the divisor results in the number required to get to the next divisor multiple, then the "magic" occurs. You would think that it's good enough to have the single modulus function, but in the case where the number is an exact multiple of the divisor, it calculates an extra multiple. ie, 24 would return 27. The additional modulus protects against this by making the addition 0.
As mentioned in a comment to the accepted answer, you can just use this:
Math.ceil(x/3)*3
(Even though it does not return 3 when x is 0, because that was likely a mistake by the OP.)
Out of the nine answers posted before this one (that have not been deleted or that do not have such a low score that they are not visible to all users), only the ones by Dean Nicholson (excepting the issue with loss of significance) and beauburrier are correct. The accepted answer gives the wrong result for negative numbers and it adds an exception for 0 to account for what was likely a mistake by the OP. Two other answers round a number to the nearest multiple instead of always rounding up, one more gives the wrong result for negative numbers, and three more even give the wrong result for positive numbers.
This function will round up to the nearest multiple of whatever factor you provide.
It will not round up 0 or numbers which are already multiples.
round_up = function(x,factor){ return x - (x%factor) + (x%factor>0 && factor);}
round_up(25,3)
27
round up(1,3)
3
round_up(0,3)
0
round_up(6,3)
6
The behavior for 0 is not what you asked for, but seems more consistent and useful this way. If you did want to round up 0 though, the following function would do that:
round_up = function(x,factor){ return x - (x%factor) + ( (x%factor>0 || x==0) && factor);}
round_up(25,3)
27
round up(1,3)
3
round_up(0,3)
3
round_up(6,3)
6
Building on #Makram's approach, and incorporating #Adam's subsequent comments, I've modified the original Math.prototype example such that it accurately rounds negative numbers in both zero-centric and unbiased systems:
Number.prototype.mround = function(_mult, _zero) {
var bias = _zero || false;
var base = Math.abs(this);
var mult = Math.abs(_mult);
if (bias == true) {
base = Math.round(base / mult) * _mult;
base = (this<0)?-base:base ;
} else {
base = Math.round(this / _mult) * _mult;
}
return parseFloat(base.toFixed(_mult.precision()));
}
Number.prototype.precision = function() {
if (!isFinite(this)) return 0;
var a = this, e = 1, p = 0;
while (Math.round(a * e) / e !== a) { a *= 10; p++; }
return p;
}
Examples:
(-2).mround(3) returns -3;
(0).mround(3) returns 0;
(2).mround(3) returns 3;
(25.4).mround(3) returns 24;
(15.12).mround(.1) returns 15.1
(n - n mod 3)+3
$(document).ready(function() {
var modulus = 3;
for (i=0; i < 21; i++) {
$("#results").append("<li>" + roundUp(i, modulus) + "</li>")
}
});
function roundUp(number, modulus) {
var remainder = number % modulus;
if (remainder == 0) {
return number;
} else {
return number + modulus - remainder;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Round up to nearest multiple of 3:
<ul id="results">
</ul>
A more general answer that might help somebody with a more general problem: if you want to round numbers to multiples of a fraction, consider using a library. This is a valid use case in GUI where decimals are typed into input and for instance you want to coerce them to multiples of 0.25, 0.2, 0.5 etc. Then the naive approach won't get you far:
function roundToStep(value, step) {
return Math.round(value / step) * step;
}
console.log(roundToStep(1.005, 0.01)); // 1, and should be 1.01
After hours of trying to write up my own function and looking up npm packages, I decided that Decimal.js gets the job done right away. It even has a toNearest method that does exactly that, and you can choose whether to round up, down, or to closer value (default).
const Decimal = require("decimal.js")
function roundToStep (value, step) {
return new Decimal(value).toNearest(step).toNumber();
}
console.log(roundToStep(1.005, 0.01)); // 1.01
RunKit example
Using remainder operator (modulus):
(n - 1 - (n - 1) % 3) + 3
By the code given below use can change any numbers and you can find any multiple of any number
let numbers = [8,11,15];
let multiple = 3
let result = numbers.map(myFunction);
function myFunction(n){
let answer = Math.round(n/multiple) * multiple ;
if (answer <= 0)
return multiple
else
return answer
}
console.log("Closest Multiple of " + multiple + " is " + result);
if(x%3==0)
return x
else
return ((x/3|0)+1)*3

Categories

Resources