mercredi 23 septembre 2015

Generate a random number and add 0 before it to ensure fixed number of digits

so I am trying to generate a random number. I am going to append the day and month as integers before the random number. This I am able to do by using the following code.

    Calendar calendar;
    calendar=Calendar.getInstance();
    int day= calendar.get(Calendar.DAY_OF_MONTH);
    int month=calendar.get(Calendar.MONTH)+1; //it treats Jan as 0 hence i add 1
    int num= Integer.valueOf(String.valueOf(month)+String.valueOf(day));

Now i need to generate a random number but add 0s before it. For example today is 21st September so numbers will look like

    921 (num) + 22334 (random num) = 92122334
    921 (num) + 2 (random num) = 92100002

Basically add 0s to the start ensuring number of digits remain the same. The use case of this is an easier way of generating unique order numbers that have an inbuilt time stamp as well. I dont expect to process more than 200 orders a day hence taking a 5 digit random number seems reasonable enough for probability of duplicates to be very small.




Aucun commentaire:

Enregistrer un commentaire