0

Do someone know if there is a method in order to round a float two numbers after the comme.

Examples :

10.28000 -> 10.3
13.97000 -> 14.0
5.41000 -> 5.4

Thanks a lot !

Regards, Sébastien ;)

4

6 回答 6

1

具有 NSRoundPlain 行为的纯 Cocoa 方式:

- (NSDecimalNumber *)decimalNumberForFloat:(float)f_

{

NSNumber *number                           = [NSNumber numberWithFloat:f_];
NSDecimal decimal                          = [number decimalValue];
NSDecimalNumber *originalDecimalNumber     = [NSDecimalNumber decimalNumberWithDecimal:decimal];
NSDecimalNumberHandler *roundingBehavior   = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain
                                              scale:0
                                              raiseOnExactness:NO
                                              raiseOnOverflow:NO
                                              raiseOnUnderflow:NO
                                              raiseOnDivideByZero:NO];

return [originalDecimalNumber decimalNumberByRoundingAccordingToBehavior:roundingBehavior];

}

由于 NSDecimalNumber 是 NSNumber 的子类,因此要获取原始浮点调用 -[NSDecimalNumber floatValue]

于 2012-08-29T03:21:13.437 回答
1

你也可以试试

float num = 10.28000
float result = (roundf(num * 10.0))/10.0;

(乘以 10,然后舍入,然后再除以 10)不要忘记 .0 以便除以浮点数而不是整数,这将再次舍入

于 2012-08-28T15:16:14.787 回答
1

使用 NSNumberFormatter 创建具有指定派系数字的字符串。

float num = 10.28000;

formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:1];

NSNumber *value = [NSNumber numberWithFloat:num];
NSString *newNumString = [formatter stringFromNumber:value];
于 2012-08-28T15:13:35.973 回答
1

尝试这个:

float aFloatValue = 3.1415926;
NSString *formatted = [NSString stringWithFormat:@"%01.1f", aFloatValue];
NSLog(@"Formatted: %@", formatted);

认为它是一个很好的旧sprintf

于 2012-08-28T15:12:14.820 回答
0

试试这个:

float myFloat = 10.4246f;
myFloat = ((int) ((myFloat * 100) + 5)) / 100.0f;
于 2012-08-28T15:16:35.210 回答
0
float fval = 1.54f;
float nfval = ceilf(fval * 10.0f + 0.5f)/10.0f;
于 2012-08-28T15:23:08.907 回答