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

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

提交回复
热议问题