简体   繁体   中英

How do I round a NSNumber to zero decimal spaces

如何将NSNumber舍入到零小数空格,在下面的行中它似乎保留小数空格:

NSNumber holidayNightCount = [NSNumber numberWithDouble:sHolidayDuration.value];

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

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

你也可以这样做: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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM