Random Number Generator

Rhane
Kilo Explorer

I am looking to create a 4 digit random number generator for a variable. Is there a specific variable type I should use? Right now I have single line variable and when I put the below script in the default value, it generates the number but there is a decimal behind it.
javascript: Math.round(Math.random()*9000) + 1000;

Could anyone answer how to truncate the decimal and what is behind that? Or if there is an easier way to make a random integer pop up in a variable?

Thanks in advance.

5 REPLIES 5

justin_drysdale
Mega Guru

I originally said use Math.floor(), however Math.round() should have the same truncating qualities. I tested your code and didnt have anything appearing to the right of the decimal point. If your code still doesn't work, you can always use parseInt on the result.


Rhane
Kilo Explorer

Modified the script and went with...

javascript: Math.floor(Math.random() * 9000).toFixed(0);

this seemed to of worked.


I would add 1 to offset Math.floor and to get a truly random (as random as js can be) number. It is always rounding down... without the +1 you would never hit the max number of the range. Probably not a big deal.



Math.floor((Math.random() * 9000) + 1).toFixed(0);


I'm trying to generate random numbers in the process of generating passwords.



Math.random() does not produce cryptographically strong results (see Math.random() - JavaScript | MDN)



window.crypto.getRandomValues() is used in browsers but doesn't appear to be available server-side in servicenow. Is there some other built-in source for strong random numbers for servicenow server-side scripts? What about other crypto services like hashing?



Cheers,


Lew