6

How do I round an NSNumber to zero decimal spaces, in the following line it seems to keep the decimal spaces:

NSNumber holidayNightCount = [NSNumber numberWithDouble:sHolidayDuration.value];
TheLearner
  • 19,387
  • 35
  • 95
  • 163

5 Answers5

14

Typically casting to int truncates. For example, 3.4 becomes 3 (as is desired), but 3.9 becomes 3 also. If this happens, add 0.5 before casting

int myInt = (int)(sHolidayDuration.value + 0.5);
Scott Marchant
  • 3,447
  • 2
  • 22
  • 29
Paul E.
  • 259
  • 1
  • 4
  • 1
    That is such a witty way of getting around the round up. I had never thought of doing it that way cause of built in rounding tools in ios. I like this answer a lot way to be thinking. – Rob Jul 02 '12 at 14:07
  • This wouldn't really work with negative numbers though – oztune Sep 21 '16 at 21:42
  • For negative numbers try this `int myInt = (int)(sHolidayDuration.value > 0 ? sHolidayDuration.value + 0.5 : sHolidayDuration.value - 0.5);` – mogelbuster Apr 29 '18 at 01:15
12

Here's a bit of a long winded approach

float test = 1.9;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setRoundingMode:NSNumberFormatterRoundHalfUp];
[formatter setMaximumFractionDigits:0];
NSLog(@"%@",[formatter  stringFromNumber:[NSNumber numberWithFloat:test]]);
[formatter release];
pir800
  • 1,012
  • 13
  • 16
  • This is more what I was looking for. In my case I wanted a decimal place or two, and in that respect this method is more powerful. – csga5000 Nov 08 '15 at 02:06
3

If you only need an integer why not just use an int

int holidayNightCount = (int)sHolidayDuration.value;

By definition an int has no decimal places

If you need to use NSNumber, you could just cast the Double to Int and then use the int to create your NSNumber.

int myInt = (int)sHolidayDuration.value;
NSNumber holidayNightCount = [NSNumber numberWithInt:myInt];
esde84
  • 211
  • 1
  • 7
1

you can also do the following: int roundedRating = (int)round(rating.floatValue);

kevinl
  • 4,194
  • 6
  • 37
  • 55
0

Floor the number using the old C function floor() and then you can create an NSInteger which is more appropriate, see: https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/floor.3.html ....

NSInteger holidayNightCount = [NSNumber numberWithInteger:floor(sHolidayDuration.value)].integerValue;

Further information on the topic here: http://eureka.ykyuen.info/2010/07/19/objective-c-rounding-float-numbers/

Or you could use NSDecimalNumber features for rounding numbers.

Oly Dungey
  • 1,603
  • 19
  • 20