r/javahelp • • Nov 28 '19

Math.Random keeps generating the same Value

I'm generating a 12 digit number for a Credit card. it must be 12 digits but random. have this line for code here :

debitCardNumber = (int) (Math.random() * Math.pow(10,12));
But, it keeps generating this value over and over: 2147483647.

In addition its 10 digits and not 12!

16 Upvotes

16 comments sorted by

View all comments

5

u/NautiHooker Software Engineer Nov 28 '19

you are casting it to an int. thats the max value for an signed 32 bit integer. try lowering the factor that u calculate with the pow function or use a datatype that is larger than an int (long comes to mind)

1

u/Alaa13 Nov 28 '19

Okay. this credit number is stored in a database. I must change the data type of that column to long as well!

1

u/PiernozYe Dec 02 '19

What I really learned in IT and as /u/Fordiman already mentioned is that you should always use String to represent a number you do not use for calculations. Don't use int/long/double/float/... for house-, phone-, creditcard-numbers, etc.

Ask yourself the question am I ever going to do something like 555-567890 + 555-098765? no, it doesn't make sense. So use String instead :)

Also for column types, you don't necessarily need to change the type, especially in big existing applications this can have a lot of drawbacks if you don't have enough tests covering your app. Parse the values using a library like jaxb or jackson almost all native Java types have something like:

- Long.parseLong(String s)

- Integer.parseInt(String s)

- Double.parseDouble(String s)

- ...

1

u/Alaa13 Dec 02 '19

Makes total sense. Thank you and y everyone who expounded.