我有代码来比较cellforrowAtIndexPath中的float或double值。我正在比较它并在评估比较值时将颜色设置为tableView单元。但是有时候,它不会进入不等于条件而值是不同的。可以告诉我什么是正确的方法我可以用来比较两个浮点数或双精度值。内部的日志不等于条件(!=)有时不打印。
我的代码如下:---
double br_preVal=[[[prevDict valueForKey:@"bestbuyprice"] valueForKey:@"text"] doubleValue];
double br_nxtVal=[[[tempDic valueForKey:@"bestbuyprice"] valueForKey:@"text"] doubleValue];
double sr_preVal=[[[prevDict valueForKey:@"bestsellprice"] valueForKey:@"text"] doubleValue];
double sr_nxtVal=[[[tempDic valueForKey:@"bestsellprice"] valueForKey:@"text"] doubleValue];
if (br_nxtVal!=br_preVal) {
NSLog(@"buy rate Not equal === and values %f,%f",br_preVal,br_nxtVal);
if (br_nxtVal>br_preVal) {
[mwCell.buyRate setBackgroundColor:t.socketHighbgColor];
mwCell.buyRate.textColor=t.socketHighfgColor;
[celllc replaceObjectAtIndex:indexPath.row withObject:t.socketHighbgColor];
}else{
[mwCell.buyRate setBackgroundColor:t.socketLowbgColor];
mwCell.buyRate.textColor=t.socketLowfgColor;
[celllc replaceObjectAtIndex:indexPath.row withObject:t.socketLowbgColor];
}
}else{
mwCell.buyRate.backgroundColor=[celllc objectAtIndex:indexPath.row];
mwCell.buyRate.textColor=([[celllc objectAtIndex:indexPath.row] isEqual:t.socketLowbgColor])?t.socketLowfgColor:t.socketHighfgColor;
}
if (sr_nxtVal!=sr_preVal) {
NSLog(@"sell rate Not equal === and values == %f,%f",sr_preVal,sr_nxtVal);
if (sr_nxtVal>sr_preVal) {
[mwCell.sellRate setBackgroundColor:t.socketHighbgColor];
[mwCell.sellRate setTextColor:t.socketHighfgColor];
[cellrc replaceObjectAtIndex:indexPath.row withObject:t.socketHighbgColor];
}else{
[mwCell.sellRate setBackgroundColor:t.socketLowbgColor];
[mwCell.sellRate setTextColor:t.socketLowfgColor];
[cellrc replaceObjectAtIndex:indexPath.row withObject:t.socketLowbgColor];
}
}else{
mwCell.sellRate.backgroundColor=[cellrc objectAtIndex:indexPath.row];
mwCell.sellRate.textColor=([[cellrc objectAtIndex:indexPath.row] isEqual:t.socketLowbgColor])?t.socketLowfgColor:t.socketHighfgColor;
}
mwCell.buyRate.text=[NSString stringWithFormat:@"%.2f",br_nxtVal];
mwCell.sellRate.text=[NSString stringWithFormat:@"%.2f",sr_nxtVal];
浮动值有点像2396.250000
答案 0 :(得分:1)
尝试比较这样
#define kVerySmallValue (0.000001)
if(fabsf(br_nxtVal - br_preVal) < kVerySmallValue) {
//// Your code
}
答案 1 :(得分:1)
通过Deafult,像3.13
这样的小数值是double
,所以如果你必须将它分配到float
varibale,请执行以下操作:
float f = 3.14f;//now it is float
见这个例子:
float f = 3.14;
if(f == 3.14)
{
NSLog(@"Equal");
}
else
{
NSLog(@"Not Equal");
}
它将打印不等于..
所以最好的方法是:
float f = 3.14;
if(f == 3.14f)
{
NSLog(@"Equal");
}
else
{
NSLog(@"Not Equal");
}
答案 2 :(得分:0)
比较浮点值的最佳方法是使用范围
if(4.0<=a&&a<=4.5)
或者您可以使用fabs(number)< comparator >fabs(number)