Home java rounding fractional numbers to whole

# rounding fractional numbers to whole

Author

Date

Category

What are the standard means for rounding numbers in Java?

• Example of rounding: 3.49 – 3, 3.50 – 4, 3.51 – 4.

1. `math.ceil (n) `– returns the smallest integer that is greater or equal
argument n.
2. `math.floor (n) `– returns the greatest integer
which is less than or equal to the argument n.
3. `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.
``````

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.
``````

`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.
``````

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
``````

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.