Java Math round method example shows how to round float or double number to an integer using the round method of the Java Math class.
How to round a number (float or double to integer) using the round method?
We can use the round
static method of the Java Math class to round a float or double number.
1 |
public static long round(double d) |
or
1 |
public static int round(float f) |
This method returns the closest integer number to the argument.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package com.javacodeexamples.mathexamples; public class RoundFloatDoubleExample { public static void main(String args[]){ float[] floatNumbers = { 5.4f, 5.49f, 5.5f, 5.9f, 0f, -0f, 0.01f, -3.4f, -3.99f }; System.out.println("Float numbers are rounded to integer"); for( float f : floatNumbers ){ System.out.println( Math.round(f) ); } double[] doubleNumbers = { 12.1d, 12.49d, 12.50d, 12.99d, -20.1d, -20.99d }; System.out.println("Double numbers are rounded to long"); for( double d : doubleNumbers ){ System.out.println( Math.round(d) ); } } } |
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Float numbers are rounded to integer 5 5 6 6 0 0 0 -3 -4 Double numbers are rounded to long 12 12 13 13 -20 -21 |
Note: The round(float f)
method returns an int value while the round(double d)
method returns a long value.
Internally, 0.5 is added to the argument number and a floor value is taken. The result is then cast to an integer value as given below.
1 2 3 4 5 |
float f1 = 5.4f; System.out.println( (int)Math.floor( f1 + 0.5 ) ); float f2 = 5.5f; System.out.println( (int)Math.floor( f2 + 0.5 ) ); |
Output
1 2 |
5 6 |
Also, check out how to get the floor number and how to get the ceiling number examples.
This example is a part of the Java Math class tutorial with examples.
Please let me know your views in the comments section below.