Written by

Question Yone Moreno · Jun 8, 2021

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.cl…

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

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

 

 

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

 

Thanks for your time, replies, and advice

Comments

Dmitry Maslennikov · Jun 8, 2021

Try these two variants

write $extract($random(10000) _ "0000", 1, 4)
write $random(10)_$random(10)_$random(10)_$random(10)
0
Yone Moreno  Jun 8, 2021 to Dmitry Maslennikov

Thanks Dmitry it is very helpful

0
Eduard Lebedyuk · Jun 8, 2021

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.

0
Yone Moreno  Jun 8, 2021 to Eduard Lebedyuk

Thanks Eduard Lebedyuk because you gave as a detailed explanation

0