如何计算iOS中浮点后的位数?

如何计算iOS中浮点后的位数?,ios,objective-c,floating-point,Ios,Objective C,Floating Point,在iOS中,如何计算浮点后的位数 例如: 3.105应返回3 3.0应该返回0 2.2应返回1 更新: 我们还需要添加以下示例。因为我想知道分数部分的位数 1e-1应返回1 尝试以下方法: NSString *enteredValue=@"99.1234"; NSArray *array=[enteredValue componentsSeparatedByString:@"."]; NSLog(@"->Count : %ld",[array[1] length]); 我使用的是

在iOS中,如何计算浮点后的位数

例如:

  • 3.105应返回3
  • 3.0应该返回0
  • 2.2应返回1
更新: 我们还需要添加以下示例。因为我想知道分数部分的位数

  • 1e-1应返回1
尝试以下方法:

NSString *enteredValue=@"99.1234";

NSArray *array=[enteredValue componentsSeparatedByString:@"."];
NSLog(@"->Count : %ld",[array[1] length]);

我使用的是以下内容:

NSString *priorityString = [[NSNumber numberWithFloat:self.priority] stringValue];
    NSRange range = [priorityString rangeOfString:@"."];
    int digits;
    if (range.location != NSNotFound) {
        priorityString = [priorityString substringFromIndex:range.location + 1];
        digits = [priorityString length];
    } else {
        range = [priorityString rangeOfString:@"e-"];
        if (range.location != NSNotFound) {
            priorityString = [priorityString substringFromIndex:range.location + 2];
            digits = [priorityString intValue];
        } else {
            digits = 0;
        }
    }

也许有一种更优雅的方法可以做到这一点,但当从32位体系结构的应用程序转换为64位体系结构时,我发现许多其他方法都失去了精度,把事情搞砸了。我是这样做的:

bool didHitDot = false;    
int numDecimals = 0;
NSString *doubleAsString = [doubleNumber stringValue];

for (NSInteger charIdx=0; charIdx < doubleAsString.length; charIdx++){

    if ([doubleAsString characterAtIndex:charIdx] == '.'){
        didHitDot = true;
    }

    if (didHitDot){
        numDecimals++;
    }
}

//numDecimals now has the right value
bool-didHitDot=false;
int numDecimals=0;
NSString*doubleAsString=[doubleNumber stringValue];
对于(NSInteger charIdx=0;charIdx
转换成NSString,然后找到点位置?@iiFreeman需要注意的是,并不是所有地区都使用点作为小数点。在iOS(使用标准Apple工具)中,不可能将3.105或2.2作为
浮点值或
双精度浮点值,因为这些值不能用二进制浮点值表示。您有其他格式的值吗?如果不是,您是否传递接近这些值的数字,例如,2.200000000017763568394002504646778106689453125而不是2.2?那么,应该使用什么标准来确定是否将其视为2.2而不是2.20000000000000017763568394002504646778106689453125?您需要首先将末端的0修剪掉。浮点始终显示8(IIRC)十进制数字。i、 e.3.00000000将返回8我想?正如David所评论的,您必须根据区域设置找到正确的十进制分隔符。@Fogmeister:您说得对,我根据所讨论的示例解决了这个问题。