ios取两个数之间的随机小数_iOS的Objective-C如何获得2小数四舍五入浮点值?

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 */

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值