Random Number Generator
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎05-08-2013 09:06 AM
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.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎05-08-2013 10:02 AM
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.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎05-08-2013 10:42 AM
Modified the script and went with...
javascript: Math.floor(Math.random() * 9000).toFixed(0);
this seemed to of worked.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎05-08-2013 10:59 AM
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);
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎06-03-2015 03:16 PM
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