Question:
Java random double generation, only want two decimals like in dollar amounts.?
Kris A.M.
2009-11-16 18:42:44 UTC
I want to generate random dollar amounts. I've already got the integer part of the amounts in my array, but I want to add cent values to it as well. I've already tried generating integers from 0-99 and dividing by 100, but I forgot that integer values less than 1 go to 0 so that was a bust.


How do you only generate random doubles to the second decimal place/(tenths and hundredths places)?
Three answers:
Sparky S
2009-11-17 01:22:08 UTC
Math.random() returns a number between 0 and 0.99999999999, so we just multiply by 100, chop off the decimal, then divide by 100.0 to get it.



You probably just forgot to divide by a double or float. 64/100 is "bust". 64/100.0 is 0.64.



double random_Dollar = (int) (Math.random() * 100) / 100.0;
anonymous
2016-12-30 20:21:36 UTC
Java Two Decimal Places
Silent
2009-11-16 18:49:15 UTC
You could always generate random doubles using the Random class and then round them off. Or just store them as full precision doubles, and format them to two decimal places when you display them.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...