How can I calculate the number of digits after the floating point in iOS?
For example:
Maybe there is a more elegant way to do this, but when converting from a 32 bit architecture app to a 64 bit architecture, many of the other ways I found lost precision and messed things up. So here's how I do it:
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
What I used is the following:
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;
}
}
Try this way:
NSString *enteredValue=@"99.1234";
NSArray *array=[enteredValue componentsSeparatedByString:@"."];
NSLog(@"->Count : %ld",[array[1] length]);