[英]Convert float to int in Objective-C
如何在舍入到下一個整數的同時將float
轉換為int
? 例如,1.00001將轉到2,而1.9999將轉到2。
float myFloat = 3.333
// for nearest integer rounded up (3.333 -> 4):
int result = (int)ceilf(myFloat );
// for nearest integer (3.4999 -> 3, 3.5 -> 4):
int result = (int)roundf(myFloat );
// for nearest integer rounded down (3.999 -> 3):
int result = (int)floor(myFloat);
// For just an integer value (for which you don't care about accuracy)
int result = (int)myFloat;
使用ceil函數:
int intValue = (int)ceil(yourValue);
您可以使用以下C方法從不同的dataTypes獲取int值。
extern float ceilf(float);
extern double ceil(double);
extern long double ceill(long double);
這些函數分別返回float,double和long double。 但這些功能的作用是獲得論證的底線或底線。 如http://en.wikipedia.org/wiki/Floor_and_ceiling_functions
然后你可以將返回值強制轉換為所需的類型。
int intVariable = (int)ceilf(floatValueToConvert);
希望它有所幫助。
如果我們有像13.123這樣的浮點值將其轉換為13之類的整數
碼
float floatnumber = 13.123; //你也可以使用CGFloat而不是float
NSLog(@"%.f",floatnumber); // use for print in command prompt
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.