How to generate 4 digit random number

How to generate a 4 digit random number in elixir/phoenix as I have to add this 4 digit number in front of the name of the uploaded file name?

I have read the function :rand.uniform(n) but it returns only a single digit. Is there any inbuilt function for it or need to create our own?

I would suggest using Enum.random(1_000..9_999)

4 Likes

Well, you could use :rand.uniform(9_000) to create a number from 1 to 9000 and then add 999 to it, this will give you four digits as well.

It is important that this will ignore 1/10 of the possible numbers (from 0 to 999). If you accept that there can be leading zeros then you can generate string with that many digits via:

charlist = :io_lib.format("~4..0B", [:rand.uniform(10_000) - 1])

List.to_string(charlist)
6 Likes

Thanks for pointing that out.

I think this is a better solution. Thanks for sharing.

Update: I have used @hauleth solution to write a generic function for getting a string of length n with just integers:

  @spec random_n_char_number_string(integer()) :: String.t()
  def random_n_char_number_string(n) do
    "~#{n}..0B"
    |> :io_lib.format([(10 |> :math.pow(n) |> round() |> :rand.uniform()) - 1])
    |> List.to_string()
  end

I hope this helps someone else.

2 Likes