Round a float up to the next integer in objective C?

前端 未结 4 1859
青春惊慌失措
青春惊慌失措 2020-12-23 16:01

How can I round a float up to the next integer value in objective C?

1.1 -> 2
2.3 -> 3
3.4 -> 4
3.5 -> 4
3.6 -> 4
1.0000000001 -> 2
         


        
相关标签:
4条回答
  • 2020-12-23 16:45

    Roundup StringFloat remarks( this is not the best way to do it )
    Language - Swift & Objective C | xCode - 9.1
    What i did was convert string > float > ceil > int > Float > String
    String Float 10.8 -> 11.0
    String Float 10.4 -> 10.0

    Swift

    var AmountToCash1 = "7350.81079101"
    AmountToCash1 = "\(Float(Int(ceil(Float(AmountToCash1)!))))"
    print(AmountToCash1) // 7351.0
    
    
    var AmountToCash2 = "7350.41079101"
    AmountToCash2 = "\(Float(Int(ceil(Float(AmountToCash2)!))))"
    print(AmountToCash2) // 7350.0
    

    Objective C

    NSString *AmountToCash1 = @"7350.81079101";
    AmountToCash1 = [NSString stringWithFormat:@"%f",float(int(ceil(AmountToCash1.floatValue)))];
    

    OR
    you can make a custom function like so
    Swift

    func roundupFloatString(value:String)->String{
      var result = ""
      result = "\(Float(Int(ceil(Float(value)!))))"
      return result
    }
    

    Called it like So

        AmountToCash = self.roundupFloatString(value: AmountToCash)
    

    Objective C

    -(NSString*)roundupFloatString:(NSString *)value{
        NSString *result = @"";
        result = [NSString stringWithFormat:@"%f",float(int(ceil(value.floatValue)))];
      return result;
    }
    

    Called it like So

        AmountToCash = [self roundupFloatString:AmountToCash];
    

    Good Luck! and Welcome! Support My answer!

    0 讨论(0)
  • 2020-12-23 16:47

    You want the ceiling function. Used like so:

    float roundedup = ceil(otherfloat);
    
    0 讨论(0)
  • 2020-12-23 16:49

    Just could not comment Davids answer. His second answer won't work as modulo doesn't work on floating-point values. Shouldn't it look like

    if (originalFloat - (int)originalFloat > 0) {
        originalFloat += 1;
        round = (int)originalFloat;
    }
    
    0 讨论(0)
  • 2020-12-23 16:55

    Use the ceil() function.

    Someone did a little math in Objective C writeup here: http://webbuilders.wordpress.com/2009/04/01/objective-c-math/

    0 讨论(0)
提交回复
热议问题