Close

Java - Math.round() Examples

Java Java API 


Class:

java.lang.Math

java.lang.Objectjava.lang.Objectjava.lang.Mathjava.lang.MathLogicBig

Methods:

public static int round(float a)

Returns the closest int to the argument, with ties rounding to positive infinity.

public static long round(double a)

Returns the closest long to the argument, with ties rounding to positive infinity.


Examples


package com.logicbig.example.math;

public class RoundExample {

public static void main(String... args) {
roundOff(4.97f);
roundOff(2.2f);
roundOff(-7.51f);
roundOff(-7.5f);
roundOff(-0.75f);
roundOff(0f / 0);
}

private static void roundOff(float value) {
int roundedValue = Math.round(value);
System.out.printf("Rounding off %6s = %s%n", value, roundedValue);
}
}

Output

Rounding off   4.97  = 5
Rounding off 2.2 = 2
Rounding off -7.51 = -8
Rounding off -7.5 = -7
Rounding off -0.75 = -1
Rounding off NaN = 0




package com.logicbig.example.math;

public class RoundExample2 {

public static void main(String... args) {
roundOff(116.97);
roundOff(71.53);
roundOff(-99.43);
roundOff(-0.19);
roundOff(0.0 / 0);
roundOff(Double.NEGATIVE_INFINITY);
}

private static void roundOff(double value) {
Long roundedValue = Math.round(value);
System.out.printf("Rounding off %6s = %s%n", value, roundedValue);
}
}

Output

Rounding off 116.97  = 117
Rounding off 71.53 = 72
Rounding off -99.43 = -99
Rounding off -0.19 = 0
Rounding off NaN = 0
Rounding off -Infinity = -9223372036854775808




See Also