如何计算iOS中浮点后的位数?
例如:
更新 我们还需要添加以下示例。因为我想知道小数部分中的位数。
答案 0 :(得分:6)
尝试这种方式:
NSString *enteredValue=@"99.1234";
NSArray *array=[enteredValue componentsSeparatedByString:@"."];
NSLog(@"->Count : %ld",[array[1] length]);
答案 1 :(得分:1)
我使用的是以下内容:
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;
}
}
答案 2 :(得分: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