Round a float up to the next integer in objective

2020-02-16 21:39发布

问题:

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

回答1:

You want the ceiling function. Used like so:

float roundedup = ceil(otherfloat);


回答2:

Use the ceil() function.

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



回答3:

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;
}


回答4:

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!