Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Math.round()

Rounds a number to the nearest integer.

Available since: Java 1.0

Syntax

static long round(double a)

Parameters

ParameterTypeDescription
adouble / floatA decimal number.

Return value

long (int for float)The nearest integer as a long; halves are rounded up.

Examples

Halves are rounded towards the larger value:

void main() {
    IO.println(Math.round(2.4));
    IO.println(Math.round(2.5));
    IO.println(Math.round(-2.5));
}

Output:

2
3
-2

Rounding to two decimal places:

void main() {
    double price = 19.98765;
    double rounded = Math.round(price * 100) / 100.0;
    IO.println(rounded);
}

Output:

19.99

Notes

For a double the result is a long, so int n = Math.round(x); does not compile — write (int) Math.round(x). Dividing by 100 instead of 100.0 gives integer division. For money BigDecimal.setScale() is safer; for display use String.format("%.2f", x).

See also

  • Math.floor() — Rounds down to the nearest integer that is less than or equal.
  • Math.ceil() — Rounds up to the nearest integer that is greater than or equal.
  • BigDecimal — An exact decimal number — for money and calculations where double rounding errors are unacceptable.
  • String.format() — Builds a string from a template with placeholders such as %s and %d.

Related recipes

In the tutorial

  • Type conversion — Automatic widening, explicit (int) casts, turning strings into numbers with Integer.parseInt and numbers into strings.

Thanks for reading!

Donate to the site — we work hard for you.