iOS 圆整浮动
我有一个具有更多小数位的浮点数,例如:
float fRes = 10.0 / 3.0;
实际上 fRes 值是 3.3333333333333 例如可以设置 2 位十进制数字:
float fRes = 10.0 / 3.0;
// fRes is 3.333333333333333333333333
float fResOk = FuncRound( fRes, 2 );
// fResOk is 3.33
提前致谢
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:
float fRes = 10.0 / 3.0;
// fRes is 3.333333333333333333333333
float fResOk = FuncRound( fRes, 2 );
// fResOk is 3.33
thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道你在哪里使用这个四舍五入的数字,但是你应该只在向用户显示它时对你的值进行四舍五入,有基于 C 的格式字符串方法来四舍五入浮点数,例如
,你可能已经读过,浮点number 是实数的近似值,因此执行
fResOk = roundf( fRes*100.0)/100.0;
可能不会得到 3.33,但会得到一个与浮动所能得到的最接近的数字点数为 3.33。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
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.假设您正在寻找正确的函数来四舍五入到一定数量的数字,您可能会发现执行以下操作最简单:
将值乘以
100
(给您 2有效数字),舍入该值,然后将其减小回最初的大小。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:
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.