ios long转float_iOS 浮点数的精确计算和四舍五入问题

iOS开发中,使用浮点数(float,double)类型运算需要注意计算精度的问题。即使只是两位小数,也会出现误差。一般和货币价格计算相关的更应注意。

项目中遇到的问题:后台返回float a;需要快速从0依次累加一个值显示到a,例如a/10,共显示10次。遇到的问题包括:

最后计算值有误差(与a有差距)

最后显示的小数点位数

首先简单贴一下定时器代码:

@property (nonatomic, strong, readonly) CADisplayLink *countDownTimer;

- (void)start

{

if (!_countDownTimer) {

_countDownTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(countDown)];

_countDownTimer.frameInterval = 1.;

}

[_countDownTimer addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];

}

- (void)countDown

{

_ascending = (_endNumber > _currentNumber);

NSInteger interval = ABS(_currentNumber - _endNumber);

NSInteger c = 0;

if (_countInterval > interval) {

c = interval;

}

else {

c = _countInterval > 0 ? _countInterval : (int)sqrtf(interval);

}

self.currentNumber = _ascending ? _currentNumber + c : _currentNumber - c;

self.text = [NSString stringWithFormat:@"%li",(long)_currentNumber];

if (self.countDownHandeler) {

self.countDownHandeler(

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值