ios 如何在iOS4 for iphone的xcode中将浮点数四舍五入为整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7720238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I round a float to a whole number in xcode for iOS4 for iphone?
提问by user988618
Possible Duplicate:
Objective-c: How to round off Float values?
可能的重复:
Objective-c:如何舍入浮点值?
I know its with the NSNumberformatter class, any sample code please?
我知道它与 NSNumberformatter 类有关,请提供任何示例代码?
回答by chown
Since int
s can't store floating-point numbers, the decimal portion of a float will be truncated and you will be left with the whole number:
由于int
s 不能存储浮点数,浮点数的小数部分将被截断,您将得到整数:
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
这是有效的,因为int
它只能存储整数,所以它只存储整数部分x
See also gnu C Library Rounding Functions:
另请参阅gnu C 库舍入函数:
— 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)
回答by Adam Eberbach
But 3.999 is also equal to 3 if you just cast it to int.
但是如果你只是将它转换为 int,3.999 也等于 3。
float value = 3.14159f;
int intValue = (int)value;
float fractional = fmodf(value, (float)intValue);
if(fractional > .5f)
intValue++;
intValue is your rounded int.
intValue 是您的舍入整数。