Java - How To - Round Integers & Decimals


Advertisements

Rounding to Nearest Integer

Here are the three easiest ways to round to the nearest integer.

1. Using Math.round()

  double randomDouble = 2.501589;

  int roundedNumber = Math.round((randomDouble) * 100.0 ) / 100.0;

  System.out.print(roundedNumber + "");

Result:

3

2. Using DecimalFormat

  double number = 2.501589;

  DecimalFormat df = new DecimalFormat("#");
  // You can also use : DecimalFormat df = new DecimalFormat("0");

  int rounded = Integer.parseInt(df.format(number));
  System.out.print(rounded + "");

Result:

3

3. Using String Formatting

  double number = 2.501589;

  int rounded = Integer.parseInt(String.format("%.0f", number));

  System.out.print(rounded + "");
  

Result:

3

Rounding to Nearest Decimal Place

Here are the three easiest ways to round to the nearest decimal place.

1. Using DecimalFormat

  double pi = 3.14159265358979323846264;

  DecimalFormat twoDecimalPlaces = new DecimalFormat("#.##");
  // You can also use : DecimalFormat df = new DecimalFormat("0.00");

  DecimalFormat fiveDecimalPlaces = new DecimalFormat("#.#####");
  // You can also use : DecimalFormat df = new DecimalFormat("0.00");

  System.out.print("Pi rounded to 2 decimal places : " + twoDecimalPlaces.format(pi) + "\n");
  System.out.print("Pi rounded to 5 decimal places : " + fiveDecimalPlaces.format(pi) + "\n");

Result:

  Pi rounded to 2 decimal places : 3.14
  Pi rounded to 5 decimal places :3.14159

2. Using String Formatting

  double pi = 3.14159265358979323846264;

  double rounded3Decimals = Double.parseDouble(String.format("%.3f", pi));
  double rounded6Decimals = Double.parseDouble(String.format("%.6f", pi));

  System.out.print("Pi rounded to 3 decimal places : " + rounded3Decimals + "\n");
  System.out.print("Pi rounded to 6 decimal places : " + rounded6Decimals + "\n");
  

Result:

  Pi rounded to 3 decimal places : 3.142
  Pi rounded to 6 decimal places : 3.141593

Rounding "Up" & "Down" to Nearest Integer

Here are the two easiest ways to round UP or DOWN to the nearest integer.

1. Rounding UP to Nearest Integer

  double pi = 3.14159265358979323846264;

  int roundedUpPi = (int) Math.ceil(pi);

  System.out.print("Pi rounded UP to nearest integer : " + roundedUpPi+ "\n");
  

Result:

  Pi rounded UP to nearest integer : 4

2. Rounding DOWN to Nearest Integer

  double e = 2.7182818284590452353602874713526;

  int roundedDownE = (int) Math.floor(e);

  System.out.print("e rounded DOWN to nearest integer : " + roundedDownE + "\n");
  

Result:

  e rounded DOWN to nearest integer : 2

java_strings.htm

Advertisements