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

前端 未结 3 444
盖世英雄少女心
盖世英雄少女心 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 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;
            }
        }
    

提交回复
热议问题