iOS的Objective-C如何获得2小数四舍五入浮点值? [英] iOS Objective-C How to get 2 decimal rounded float value?

查看:778
本文介绍了iOS的Objective-C如何获得2小数四舍五入浮点值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个

  float a = 1412.244019; 

我需要四舍五入到最接近的秒数,如1412.24000000。我明白,如果我想提出只有两个小数我使用%.2f,但事实并非如此。我需要一个新的数学原因作为一个浮动。

我已经尝试了几个方法发现在stackoverflow没有运气。我使用的比较明显,我在下面提到,但仍然没有运气使用它。你能明白为什么魔法不会发生吗?



PS:它有时会达到预期的效果,不总是,这让我想......嗯......

预先感谢。

代码:

  float a = 1412.244019; 
NSLog(@a is%f,a); //输出a是1412.244019
a = [[NSString stringWithFormat:@%。2f,a] floatValue];
NSLog(@a is%f,a); //输出a是1412.239990

编辑:



SEEMS就像我在上述手术后使用float a时一样,它认为是1412.240000,尽管NSLog的说法不一样...奇怪。
但是我得到了我想要的东西,所以很荣幸没有浪费时间追逐任何东西)



编辑我很乐意选择你所有正确的答案,但因为我只能选择一个,我选择了第一个好的答案与额外的解释(最后两个)。

解决方案



  CGFloat val = 37.777779; 

CGFloat rounded_down = floorf(val * 100)/ 100; / *结果:37.77 * /
CGFloat nearest = floorf(val * 100 + 0.5)/ 100; / *结果:37.78 * /
CGFloat rounded_up = ceilf(val * 100)/ 100; / *结果:37.78 * /

来源:舍入数到2小数位在C中



补全:你只是没有控制计算机将如何存储浮点值。

所以这些舍入值可能不完全是明显的十进制值,但它们将是非常非常接近,这是你将有最大的保证。


I have a

float a = 1412.244019;

and I need a to be rounded to the nearest second decimal like 1412.24000000. I understand that if i want to present a with only two decimals i use %.2f, but that is NOT the case. I need the new a for mathematical reasons as a float.

I have tried a couple of methods found on stackoverflow without luck. The more obvious one i used, i mention below, but still had no luck using it. Can YOU see why the magic is not happening?

PS: It does do the desired effect sometimes, NOT always, which gets me thinking... hmmm...

Thanks in advance.

Code:

float a = 1412.244019;
NSLog(@"a is %f", a); //output a is 1412.244019
a = [[NSString stringWithFormat:@"%.2f", a] floatValue];
NSLog(@"a is %f", a); //output a is 1412.239990

EDIT:

SEEMS like when i am using the float a after the above surgery, it is considering it to be 1412.240000 eventhough the NSLog says differently... strange. But i am getting what I want, so Kudos for wasted time chasing nothing :)

EDIT I would love to choose you all as correct answers, but since i can only choose one, i chose the first good answer with extra explanation (of the two last).

解决方案

Have you tried this?

CGFloat val = 37.777779;

CGFloat rounded_down = floorf(val * 100) / 100;   /* Result: 37.77 */
CGFloat nearest = floorf(val * 100 + 0.5) / 100;  /* Result: 37.78 */
CGFloat rounded_up = ceilf(val * 100) / 100;      /* Result: 37.78 */

source : Rounding Number to 2 Decimal Places in C

Complementing: You just don't have control about how the computer will store the float value.

So these rounded values may not be EXACTLY the "obvious" decimal values, but they will be very very close, and that's the max guarantee you will have.

这篇关于iOS的Objective-C如何获得2小数四舍五入浮点值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆