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];
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];
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];
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);
int myInt = (int)(sHolidayDuration.value > 0 ? sHolidayDuration.value + 0.5 : sHolidayDuration.value - 0.5);
–
Mode 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];
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];
you can also do the following: int roundedRating = (int)round(rating.floatValue);
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.
© 2022 - 2024 — McMap. All rights reserved.