Search code examples
scalascala-gatling

How to generate 15 digit random number using Scala


I am new to Scala programming, I want to generate random number with 15 digits, So can you please let share some example. I have tried the below code to get the alpha number string with 10 digits.

  var ranstr = s"${(Random.alphanumeric take 10).mkString}"
  print("ranstr", ranstr)

Solution

  • You need to pay attention to the return type. You cannot have a 15-digit Int because that type is a 32-bit signed integer, meaning that it's maximum value is a little over 2B. Even getting a 10-digit number means you're at best getting a number between 1B and the maximum value of Int.

    Other answers go in the detail of how to get a 15-digits number using Long. In your comment you mentioned between, but because of the limitation I mentioned before, using Ints will not allow you to go beyond the 9 digits in your example. You can, however, explicitly annotate your numeric literals with a trailing L to make them Long and achieve what you want as follows:

    Random.between(100000000000000L, 1000000000000000L)
    

    Notice that the documentation for between says that the last number is exclusive.

    If you're interested in generating arbitrarily large numbers, a String might get the job done, as in the following example:

    import scala.util.Random
    import scala.collection.View
    
    def nonZeroDigit: Char = Random.between(49, 58).toChar
    def digit: Char = Random.between(48, 58).toChar
    
    def randomNumber(length: Int): String = {
      require(length > 0, "length must be strictly positive")
      val digits = View(nonZeroDigit) ++ View.fill(length - 1)(digit)
      digits.mkString
    }
    
    randomNumber(length = 1)
    randomNumber(length = 10)
    randomNumber(length = 15)
    randomNumber(length = 40)
    

    Notice that when converting an Int to a Char what you get is the character encoded by that number, which isn't necessarily the same as the digit represented by the Int itself. The numbers you see in the functions from the ASCII table (odds are it's good enough for what you want to do).

    If you really need a numeric type, for arbitrarily large integers you will need to use BigInt. One of its constructors allows you to parse a number from a string, so you can re-use the code above as follows:

    import scala.math.BigInt
    
    BigInt(randomNumber(length = 15))
    BigInt(randomNumber(length = 40))
    

    You can play around with this code here on Scastie.

    Notice that in my example, in order to keep it simple, I'm forcing the first digit of the random number to not be zero. This means that the number 0 itself will never be a possible output. If you want that to be the case if one asks for a 1-digit long number, you're advised to tailor the example to your needs.