ios Objective-C 浮点舍入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4702408/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:32:50  来源:igfitidea点击:

Objective-C Float Rounding

iphoneobjective-ciosfloating-pointrounding

提问by CodeGuy

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”

采纳答案by Dave

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);

回答by Jonathan Grynspan

Use the C standard function family round(). roundf()for float, round()for double, and roundl()for long double. You can then cast the result to the integer type of your choice.

使用 C 标准函数族round()roundf()对于floatround()对于doubleroundl()对于long double。然后,您可以将结果转换为您选择的整数类型。

回答by vp2698

For round floatto nearest integer use roundf()

对于舍入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

回答by capikaw

The easiest way to round a float in objective-c is lroundf:

在objective-c中舍入浮点数的最简单方法是lroundf

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

回答by Arvind Kanjariya

If in case you want round float value in integer below is the simple method for rounding the float value in objective C.

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

int roundedValue = roundf(Your float value);

回答by NSResponder

Check the manual page for rint()

检查手册页 rint()

回答by Lil C Big Durkee

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)