Summary of floor, round and ceil of Java math

Source: Internet
Author: User

Floor returns the maximum integer not greater
Round is the calculation of 4 homes and 5 homes, and the input is an integer greater than it (when-1.5 is displayed, the result obtained after rounding is not what we expect, the solution is to first take the absolute value for him, and then use the round method)

Round method, which indicates "Rounding". The algorithm is math. floor (x + 0.5), which adds 0.5 to the original number and then rounds down. Therefore, math. the result of round (11.5) is 12, math. the result of round (-11.5) is-11.

Ceil is the smallest integer not less than him.

Look at the example

Math. Floor Math. Round Math. ceil
1.4 1 1 2
1.5 1 2 2
1.6 1 2 2
-1.4 -2 -1 -1
-1.5 -2 -1 -1
-1.6 -2 -2 -1

The test procedure is as follows:

Public class mytest {<br/> Public static void main (string [] ARGs) {<br/> double [] Nums = {1.4, 1.5, 1.6,-1.4, -1.5,-1.6 }; <br/> for (double num: Nums) {<br/> test (Num ); <br/>}</P> <p> Private Static void test (double num) {<br/> system. out. println ("math. floor ("+ num +") = "+ math. floor (Num); <br/> system. out. println ("math. round ("+ num +") = "+ math. round (Num); <br/> system. out. println ("math. ceil ("+ num +") = "+ math. ceil (Num); <br/>}< br/>}

Running result
Math. Floor (1.4) = 1.0
Math. Round (1.4) = 1
Math. Ceil (1.4) = 2.0
Math. Floor (1.5) = 1.0
Math. Round (1.5) = 2
Math. Ceil (1.5) = 2.0
Math. Floor (1.6) = 1.0
Math. Round (1.6) = 2
Math. Ceil (1.6) = 2.0
Math. Floor (-1.4) =-2.0
Math. Round (-1.4) =-1
Math. Ceil (-1.4) =-1.0
Math. Floor (-1.5) =-2.0
Math. Round (-1.5) =-1
Math. Ceil (-1.5) =-1.0
Math. Floor (-1.6) =-2.0
Math. Round (-1.6) =-2
Math. Ceil (-1.6) =-1.0

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.