Objective-c floating point conversion integer (rounding up, rounding down)

Source: Internet
Author: User

Objective-c expands C, and naturally many usages are consistent with C. For example, the floating-point number is converted into integers, there are four cases.
1. Simple and rough, direct conversion

float f = 1.5; int a; a = (int)f; NSLog("a = %d",a);

The output result is 1. (int) is a forced type conversion that discards the decimal part of a floating-point number.

2. Gaussian function, rounding down

1.6; int a; a = floor(f); NSLog("a = %d",a);

The output result is 1. The floor () method is rounded down, similar to the Gaussian function in mathematics []. Gets the largest integer that is not larger than the floating-point number, which is the part of the floating-point number for a positive number and minus 1 for the complex number after the floating-point part is discarded.

3.ceil function, rounding up.

1.5; int a; a = ceil(f); NSLog("a = %d",a);

The output result is 2. The Ceil () method is rounded up to get the smallest integer not less than the floating-point number, and for positive numbers it discards the floating-point number and adds 1, which is the part of the floating-point number that is discarded for the plural.

4. Rounding by forcing type conversion.

float f = 1.5; int a; a = (int)(f+0.5); NSLog("a = %d",a);

Objective-c floating point conversion integer (rounding up, rounding down)

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.