views:

46

answers:

2

Hi all,

This seems really simple but I can't see that NSNumberFormatter has a function for this which is strange. I have a number, lets say 4.1. I want to round that to 5. I figured if I used NSNumberFormatter and set the roundingMode to NSNumberFormatterRoundUp I would get the desired result. But the only way I seem to be able get my number to round now is either stringFromNumber or numberFromString. Seems odd that I just can't keep it a number.

I know I could just convert the string to a number but it seems like such a waste. Wanted to know if there was a different way (round() wouldn't round up if the number was 4.1) or if there is a method I missed looking through the class ref.

Cheers

+5  A: 

You could use the standard c function ceil

CGFloat number = 4.1;
CGFloat roundedUp = ceil( number ); // Will be 5.0
aegzorz
See http://www.codecogs.com/reference/c/math.h/ceil.php
Jon Rodriguez
Make sure `number` is a float and not an NSNumber, though. Otherwise use `[number floatValue]`.
Frank Schmitt
Cheers, worked like a charm. Got confused for a sec though cause all my numbers were int's, changed one to a double so it would calculate right
Rudiger
+2  A: 

You can use native C functions in Objective C. What you are after is ceil(). If you already have an NSNumber you can use the object methods such as floatValue to get a native C float.

float num = [ns_number floatValue];
num = ceil(num);
Jason McCreary