What are the standard means for rounding numbers in Java?
- Example of rounding: 3.49 – 3, 3.50 – 4, 3.51 – 4.
Answer 1, Authority 100%
math.ceil (n)
– returns the smallest integer that is greater or equal
argument n.math.floor (n)
– returns the greatest integer
which is less than or equal to the argument n.math.round (N)
returns
An integer nearest to argument N (round n).
Example with Ceil
:
int rexult = (int) math.ceil (3.8);
System.out.PrintLN (Result); //4
INT RESULT = (INT) Math.ceil (3.3);
System.out.PrintLN (Result); //4
Example with Floor
:
int rexult = (int) math.floor (3.8);
System.out.PrintLN (Result); // 3.
INT RESULT = (INT) Math.floor (3.3);
System.out.PrintLN (Result); // 3.
Example with Round
:
int frame = (int) math.round (3.8);
System.out.PrintLN (Result); //4
INT RESULT = (INT) Math.round (3.3);
System.out.PrintLN (Result); // 3.
Answer 2, Authority 16%
During my youth, when there were no such smart ROUND / CEIL / FLOOR
, rounding was done about this:
double x = 8.3;
int i;
i = (int) (x + 0.5); // Round
i = (int) (x); // Floor
i = (int) (x + 1); // Ceil.
Answer 3, Authority 3%
math.round ()
method Returns Long
or int
(integer), nearest to real number, double
or Float
, argument. In other words, it carries out rounding to integers.
double d1 = 1.49;
Double d2 = 1.50;
Math.round (D1);
Math.round (D2);
and result:
d1 = 1
d2 = 2.
Answer 4
Here is the right code:
double b = 6.7;
Float C = 4.5F;
Double H = 4.1;
System.Out.printLN (Math.round (H)); // Output to the screen The integer value of type int to the farmost number (4.5 will have a number 5)
System.Out.PrintLN (Math.Floor (C)); / * rounds the number of type float down to the nearest to Double * /
System.out.print (Math.ceil (H)); // Rounds the number of type Double up to the type Double