I'm using if (this.getField("Form No").valueAsString=="") {
this.getField("Form No").value = util.printf("%05d", Math.floor((Math.random() * 99999) + 1000));
}
In an attempt to fill a text field with a random 5 digit number in a PDF upon open. It seems to generate a number ranging from 5-6 digits instead of exactly 5.
What am I doing wrong?
Thanks for the reples. I'm sorry but I'm very inexperienced when it comes to javascript. I assume you mean:
function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; }
But how would I actually put this in my own code with the 10000 as min and 99999 as max?
The expression rnd() * 99999
will give you a number in the range 0..99999
(all ranges here are inclusive at the lower end and exclusive at the upper, so this range does not include 99999
). When you add 1000
to that you'll get a number in the range 1000..100999
.
That's four-, five-, or six-digits, though you'll never see four-digit ones since you print them with %05d
forcing a leading zero. However, the %05d
specifies a minimum field width so will pass six-digit numbers through unchanged hence why you see five- and six-digit ones.
If you're after a five digit number without leading zeroes, you should instead be getting a number in the range 0..90000then adding ten thousand to translate that to
10000..100000`, something like:
Math.floor(Math.random() * 90000) + 10000
Or, using a generalised function:
function getRangeVal(lo, hi) {
return Math.floor(Math.random() * (hi + 1 - lo)) + lo;
}
val = getRangeVal(10000, 99999);
This latter method has the advantage of being able to generate numbers from an arbitrary range without having to think too much. For example, it will also easily do a five-digit number from 0..100000
with:
val = getRangeVal(0, 100000);
if that's what you were after (your question is a little vague on that, since it both adds an offset as if you wanted it to start at 10000
and uses %05d
as if you were allowing for numbers below 10000
).
So, bottom line, if you're after numbers in 10000..100000
and `0..100000 (as string padded to five characters), use respectively:
strVal = util.printf("%5d",getRangeVal(10000, 99999));
strVal = util.printf("%05d",getRangeVal(0, 99999));