How to calculate number of digits after floating point in iOS?

前端 未结 3 445
盖世英雄少女心
盖世英雄少女心 2021-01-21 00:21

How can I calculate the number of digits after the floating point in iOS?

For example:

  • 3.105 should return 3
  • 3.0 should return 0
  • 2.2 shou
相关标签:
3条回答
  • 2021-01-21 00:50

    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
    
    0 讨论(0)
  • 2021-01-21 01:02

    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;
            }
        }
    
    0 讨论(0)
  • 2021-01-21 01:05

    Try this way:

    NSString *enteredValue=@"99.1234";
    
    NSArray *array=[enteredValue componentsSeparatedByString:@"."];
    NSLog(@"->Count : %ld",[array[1] length]);
    
    0 讨论(0)
提交回复
热议问题