Question
Yone Moreno · Jun 8

Generate random number with 4 digits

Hello, first of all thanks for your time reading this question and thank you for your replies

 

We would need some help

We are trying to create a function to generate a random number with always 4 digits

 

We have already read the following topics:

https://docs.intersystems.com/irislatest/csp/docbook/DocBook.UI.Page.cls...

https://community.intersystems.com/post/how-generate-random-string-fixed...

https://docs.intersystems.com/latest/csp/docbook/DocBook.UI.Page.cls?KEY...

 

 

How would you recommend to write a function to handle this use case?

 

Thanks for your time, replies, and advice

00
1 1 5 111
Log in or sign up to continue

Try these two variants

write $extract($random(10000) _ "0000", 1, 4)
write $random(10)_$random(10)_$random(10)_$random(10)

Thanks Dmitry it is very helpful

There's a standard method for it:

write ##class(%PopulateUtils).Integer(min, max)

If you're okay with 0 as a first digit you can use:

write $tr($j($random(10000),4)," ", 0)

Note, that $random is preudo-random, if you require strictly random values you should use the GenCryptRand() method of the %SYSTEM.Encryption class.

Thanks Eduard Lebedyuk because you gave as a detailed explanation