Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I round a NSNumber to zero decimal spaces

Tags:

objective-c

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];
like image 228
TheLearner Avatar asked Aug 02 '10 13:08

TheLearner


People also ask

How do you round a number in Objective C?

Use lroundf() to round a float to integer and then convert the integer to a string.

How do you round a double to two decimal places in Swift?

Rounding Numbers in Swift By using round(_:) , ceil(_:) , and floor(_:) you can round Double and Float values to any number of decimal places in Swift.


2 Answers

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);
like image 177
Paul E. Avatar answered Oct 12 '22 18:10

Paul E.


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];
like image 25
pir800 Avatar answered Oct 12 '22 18:10

pir800