在Objective-c中如何舍入Float值?
答案 0 :(得分:144)
除了其他答案:
float theFloat = 1.23456;
int rounded = roundf(theFloat); NSLog(@"%d",rounded);
int roundedUp = ceil(theFloat); NSLog(@"%d",roundedUp);
int roundedDown = floor(theFloat); NSLog(@"%d",roundedDown);
// Note: int can be replaced by float
对于四舍五入到特定小数,请参阅Alex Kazaev提到的问题。
答案 1 :(得分:18)
函数lroundf()
将执行此操作:
float a=20.49;
int myInt = lroundf(a);
答案 2 :(得分:1)
转换为int然后转换回float。
CGFloat *myFloat = 100.765;
NSInteger *myInteger = myFloat;
CGFloat *newFloat = myInteger;
这将有效