简体   繁体   English

如何将NSNumber舍入为零小数空格

[英]How do I round a NSNumber to zero decimal spaces

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

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

Typically casting to int truncates. 通常转换为int truncates。 For example, 3.4 becomes 3 (as is desired), but 3.9 becomes 3 also. 例如,3.4变为3(根据需要),但3.9也变为3。 If this happens, add 0.5 before casting 如果发生这种情况,请在投射前添加0.5

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

int holidayNightCount = (int)sHolidayDuration.value;

By definition an int has no decimal places 根据定义,int没有小数位

If you need to use NSNumber, you could just cast the Double to Int and then use the int to create your NSNumber. 如果需要使用NSNumber,可以将Double转换为Int,然后使用int创建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 .... 使用旧的C函数floor()对数字进行设置,然后您可以创建更合适的NSInteger,请参阅: 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/ 有关该主题的更多信息,请访问: http//eureka.ykyuen.info/2010/07/19/objective-c-rounding-float-numbers/

Or you could use NSDecimalNumber features for rounding numbers. 或者您可以使用NSDecimalNumber功能来舍入数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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