how-to

Math

Rounding

In java exists several rounding functions

Math.floor()

This function returns double, as lower integer value from passed parameter.

System.out.println( Math.floor( 1.49 ) );
System.out.println( Math.floor( 0.56 ) );
System.out.println( Math.floor( -0.56 ) );

Output is:

1.0
0.0
-1.0

Math.ceil()

This function returns double, as greater integer value from passed parameter.

System.out.println( Math.ceil( 1.49 ) );
System.out.println( Math.ceil( 0.56 ) );
System.out.println( Math.ceil( -0.56 ) );

Output is:

2.0
1.0
-0.0

Math.round()

Typical rounding function to long.

System.out.println( Math.round( 1.49 ) );
System.out.println( Math.round( 1.5 ) );
System.out.println( Math.round( 0.56 ) );
System.out.println( Math.round( -0.56 ) );

Output is:

1
2
1
-1

Math.rind()

This function is very similar to Math.round(), returns double, but its behavior is quite confusing. Function internaly works with 2^52 value for calc unter/overflowing. My recomendation is to use rather Math.round().

Example is here:

System.out.println( Math.rint( 1.5 ) );
System.out.println( Math.rint( 2.5 ) );
System.out.println( Math.rint( 3.5 ) );
System.out.println( Math.rint( 4.5 ) );
System.out.println( Math.rint( 5.5 ) );
System.out.println( Math.rint( 6.5 ) );

Output is:

2.0
2.0
4.0
4.0
6.0
6.0