简体   繁体   English

Objective-C Float Rounding

[英]Objective-C Float Rounding

How might I round a float to the nearest integer in Objective-C: 我怎样才能将浮点数舍入到Objective-C中最接近的整数:

Example: 例:

float f = 45.698f;
int rounded = _______;
NSLog(@"the rounded float is %i",rounded);

should print "the rounded float is 46" 应打印“圆形浮子是46”

Use the C standard function family round() . 使用C标准函数系列round() roundf() for float , round() for double , and roundl() for long double . roundf()表示floatround()表示doubleroundl()表示long double You can then cast the result to the integer type of your choice. 然后,您可以将结果转换为您选择的整数类型。

The recommended way is in this answer: https://stackoverflow.com/a/4702539/308315 建议的方法是在这个答案: https//stackoverflow.com/a/4702539/308315


Original answer: 原始答案:

cast it to an int after adding 0.5. 添加0.5后将其强制转换为int。

So 所以

NSLog (@"the rounded float is %i", (int) (f + 0.5));

Edit: the way you asked for: 编辑:您要求的方式:

int rounded = (f + 0.5);


NSLog (@"the rounded float is %i", rounded);

The easiest way to round a float in objective-c is lroundf : 在objective-c中lroundf浮点数的最简单方法是lroundf

float yourFloat = 3.14;
int roundedFloat = lroundf(yourFloat); 
NSLog(@"%d",roundedFloat);

For round float to nearest integer use roundf() 对于round float到最接近的整数,请使用roundf()

roundf(3.2) // 3
roundf(3.6) // 4

You can also use ceil() function for always get upper value from float . 您也可以使用ceil()函数始终从float获取上限值。

ceil(3.2) // 4
ceil(3.6) // 4

And for lowest value floor() 并为最低价格floor()

floorf(3.2) //3
floorf(3.6) //3

如果你想要整数下面的圆形浮点数值是在目标C中舍入浮点值的简单方法。

int roundedValue = roundf(Your float value);

查看rint()的手册页

let's do tried and checkout 让我们尝试和结帐

//Your Number to Round (can be predefined or whatever you need it to be)
float numberToRound = 1.12345;
float min = ([ [[NSString alloc]initWithFormat:@"%.0f",numberToRound] floatValue]);
float max = min + 1;
float maxdif = max - numberToRound;
if (maxdif > .5) {
    numberToRound = min;
}else{
    numberToRound = max;
}
//numberToRound will now equal it's closest whole number (in this case, it's 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM