2012-01-09 54 views
10

如何將float轉換爲int,同時舍入到下一個整數?例如,1.00001會去2和1.9999會去2.在Objective-C中將浮點數轉換爲int

+0

請逆向工程&這裏http://stackoverflow.com/questions/286756/how-do-i-convert-a-float-to-an-int-in -objective-c – wanmuz 2012-01-09 08:16:07

+0

你爲什麼使用float而不是double?另一個問題,你有沒有想過要買一本關於C語言的書?每一個聽到的功能層,小區和圓? – gnasher729 2014-05-29 07:45:03

回答

61
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; 
+0

謝謝!它爲我工作。 – Raja 2017-05-03 06:07:56

11

使用ceil功能:

int intValue = (int)ceil(yourValue); 
1

您可以使用下面的C方法從不同的數據類型得到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); 

希望它有幫助。

0

如果我們有像13.123浮點值將其轉換成整數像13

代碼

浮子floatnumber = 13.123; //你也可以使用CGFloat的,而不是浮

NSLog(@"%.f",floatnumber); // use for print in command prompt