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(