iOS 轮一个浮点数

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

iOS round a float

objective-ciosfloating-pointrounding

提问by ghiboz

I have a floating point number that have more decimal digits, for example:

我有一个具有更多十进制数字的浮点数,例如:

float fRes = 10.0 / 3.0;

actually the fRes value is 3.3333333333333 it's possible set for example 2 decimal digits:

实际上 fRes 值是 3.3333333333333 可以设置例如 2 个十进制数字:

float fRes = 10.0 / 3.0;
// fRes is 3.333333333333333333333333
float fResOk = FuncRound( fRes, 2 );
// fResOk is 3.33

thanks in advance

提前致谢

回答by Nathan Day

I don't know where you are using this rounded number, but you should only round your value when displaying it to the user, there are C based format string ways to round floating point numbers for example

我不知道你在哪里使用这个四舍五入的数字,但你应该只在向用户显示时四舍五入你的值,例如有基于 C 的格式字符串方法来四舍五入浮点数

[NSString stringWithFormat:@"%.2f", value];

as you may have already read, floating point number are approximations of real numbers, so doing fResOk = roundf( fRes*100.0)/100.0;may not give you 3.33 but a number which is just as close as you can get with floating point number to 3.33.

您可能已经读过,浮点数是实数的近似值,因此这样做fResOk = roundf( fRes*100.0)/100.0;可能不会给您 3.33,而是一个与浮点数与 3.33 最接近的数字。

回答by gaige

Assuming that you're looking for the correct function to round to a certain number of digits, you'll probably find it easiest to do the following:

假设您正在寻找四舍五入到特定位数的正确函数,您可能会发现执行以下操作最简单:

fResOk = roundf( fRes*100.0)/100.0;

That will multiply the value by 100(giving you your 2 digits of significance), round the value, and then reduce it back to the magnitude you originally started with.

这会将值乘以100(为您提供 2 位重要数字),舍入该值,然后将其减少到您最初开始时的大小。