开发者

How do I round a float to a whole number in xcode for iOS4 for iphone? [duplicate]

开发者 https://www.devze.com 2023-04-12 15:44 出处:网络
This question already has answers here: Closed 11 years ago. 开发者_JAVA百科Possible Duplicate: Objective-c: How to round off Float values?
This question already has answers here: Closed 11 years ago.

开发者_JAVA百科Possible Duplicate:

Objective-c: How to round off Float values?

I know its with the NSNumberformatter class, any sample code please?


Since ints can't store floating-point numbers, the decimal portion of a float will be truncated and you will be left with the whole number:

float x = 3.14159;
int y = (int)x;

This works because the int is only capable of storing integers, so it simply stores the integer portion of x


See also gnu C Library Rounding Functions:

 — Function: double ceil (double x)
 — Function: float ceilf (float x)
 — Function: long double ceill (long double x)
 — Function: double floor (double x)
 — Function: float floorf (float x)
 — Function: long double floorl (long double x)
 — Function: double trunc (double x)
 — Function: float truncf (float x)
 — Function: long double truncl (long double x)
 — Function: double rint (double x)
 — Function: float rintf (float x)
 — Function: long double rintl (long double x)
 — Function: double nearbyint (double x)
 — Function: float nearbyintf (float x)
 — Function: long double nearbyintl (long double x)
 — Function: double round (double x)
 — Function: float roundf (float x)
 — Function: long double roundl (long double x)
 — Function: long int lrint (double x)
 — Function: long int lrintf (float x)
 — Function: long int lrintl (long double x)
 — Function: long long int llrint (double x)
 — Function: long long int llrintf (float x)
 — Function: long long int llrintl (long double x)
 — Function: long int lround (double x)
 — Function: long int lroundf (float x)
 — Function: long int lroundl (long double x)
 — Function: long long int llround (double x)
 — Function: long long int llroundf (float x)
 — Function: long long int llroundl (long double x)
 — Function: double modf (double value, double *integer-part)
 — Function: float modff (float value, float *integer-part)
 — Function: long double modfl (long double value, long double *integer-part)


But 3.999 is also equal to 3 if you just cast it to int.

float value = 3.14159f;
int intValue = (int)value;
float fractional = fmodf(value, (float)intValue);
if(fractional > .5f)
    intValue++;

intValue is your rounded int.

0

精彩评论

暂无评论...
验证码 换一张
取 消