Java Course 3: Random Numbers and Rounding

Random Numbers

Math.random() returns a random double between 0 and <1. Examples are 0.3332, 0.77777779 and 0.1113

To find a random number between 1 and 100, you’d need to do something like this:

double num = Math.random()*100;
int ran = (int)num+1;
System.out.println(ran);

Rounding and Formatting Decimals

double d = 3122.656774;
double roundUp = Math.round(d);
System.out.println(roundUp);

//Roundup to two decimal places
double roundUp2dp = Math.round(d*100)/100.0;
System.out.println(roundUp2dp);

//Formatting a number
//Note that the output is a string
DecimalFormat f = new DecimalFormat("#,###.00");
System.out.println(f.format(d));

Sample Formats

PatternNumberFormatted
###.###123.456123.456
###.#123.456123.5
###,###.##123456.789123,456.79
000.###9.95009.95
##0.###0.950.95

Exercise: Fahrenheit to Celsius

Here are the formulas to convert from Fahrenheit to Celsius and back again.

  • °F to °C: Deduct 32, then multiply by 5, then divide by 9
  • °C to °F: Multiply by 9, then divide by 5, then add 32
  1. Write a program to convert Fahrenheit to Celsius. Use the test data below to check your program.
  2. Now write a program to convert Celsius to Fahrenheit. Again, use the test data to check your program.

Test Data

CF
032
1254
100212
-327
-180
-23-10

Leave a Comment